Passing command line arguments to awk

How can I pass a command line argument such as $1 or $2 into an awk script?

I have written a shell script that includes some awk programming and i need to be able to call that program by typing ./program inputword and then search for inputword within awk.

For example, if I had a datafile with the following contents:


and i wanted to write a script to search through that file for a name that I give at the command line

awk '
$4 ~ /b/ {print $4} ' datafile

i would like to do it like this

awk '
$4 ~ /input from command line such as $1/ {print $4}' datafile

I have tried this:

awk '
$4 ~ /inputword/ {print $4}' inputword=$1 datafile

without any luck

I have to be able to run the program without having to type something like

awk -f scriptfile datafile

as it gets to confusing.

Can anyone help?

Who is Participating?
ahoffmannConnect With a Mentor Commented:
2 possibilities:

1. use gawk -v varname=inputword -f awkscript datafile
   (use  varname in you awk script)

2. using traditional awk is somehow triky, you must pass in you
   strings via the data stream and then identify it uniqely

   /^SPECIAL_VALUE/ { inputword = $2; next; }
   {   # rest of script }

   call this script as follows:

   (echo SPECIAL_VALUE "your_value"; cat datafile)|awk -f script

   Keep in mind that SPECIAL_VALUE *must not* appear in datafile.
(echo SPECIAL_VALUE inputword; cat datafile) | awk '/^SPECIAL_VALUE/ { pattern=$2;} $4 ~ pattern {print $4}'
awk "\$4 ~ /$1/ {print \$4}"  datafile
ianfosterAuthor Commented:
I've installed gawk on the machine but still no luck :(

Here's another example:



echo "Here we go!"

# the rest of the shell script goes here

gawk -v input=$1 -F: '
$1 ~ /input/ {print $1}' datafile


datafile contents as follows


I call the program as follows

/gawkprog a

it should print out "a" for each line but I get nothing.

it does read in the $1 part because I can do this                  

gawk -v input=$1 -F: '
{print input} ' datafile

and run it ./gawkprog a

and it will print out


so the problem seems to be that gawk doesnt like matching things with
the input part.

any ideas?
gawk -v input=$1 -F: '$1 ~ input {print $1}' datafile

BTW, ozo's solution works also inside a shell script
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.