How to use shell variable in awk?

How do you use a shell variable in awk? I am using Solaris 10 and don't have GNU products installed.

File (transportation.txt) contents:

car
boat 
airplane
snowmobile
bicycle
sled

This awk statment works (prints from the car line down to bicycle

awk '/car/,/bicycle/' transportation.txt

But what if instead of car I use a shell variable named vehicle (where the variable can be any value) passed by the user?

This line doesn't work (what's missing?)

awk '/$vehicle/,/bicycle/' transportation.txt

I have a blog on this
Chi Hung Chan: Four Ways to Pass Shell Variables in AWK

Thanks for the info. How do you apply the first way and second way to my awk command line. Sorry, I'm new to awk.

---------- Post updated at 09:19 PM ---------- Previous update was at 08:09 PM ----------

Will this work?

awk 'END{'/a/,/bicycle/}' a=$vechicle transportation.txt

thanks for the help.......

vechicle="car"
awk '/'$vehicle'/,/bicycle/' transportation.txt

Since you are using '/.../' , second way cannot be used.

1 Like

Do I need the first line if $vechicle is defined elsewhere? $vehicle with be defined by the user and set in the script. set vechicle=$argv[1].

You should have nawk on a Solaris 10 box, so either of these should work and avoid any nasty quoting games:


awk 'match( $0, v ),/bicycle/' v="$vehicle" input-file

nawk -v v="$vehicle" 'match( $0, v ),/bicycle/' input-file

And, as long as vehicle is set before you use it, you should be fine.

1 Like

Agama, can you explain the lines of code? How does it know to stop searching at bicycle? Should the bar part of your code be bicycle?

Oops, I was testing with a file that had foo and bar, and didn't change it when I put it into the example.

Yes! It should be bicycle.

Sorry about that!

awk '$0~t,/bicycle/' t="$vehicle" infile

On Solaris use /usr/xpg4/bin/awk

The first 3 examples will only work for variables without spaces or special characters, because there are no double quotes around them (this is not a variable assignment). It is perhaps also good to point out that the second example will not work in the BEGIN section.