passing command line arguments to awk

Neil Smithline neil at sunybcs.UUCP
Mon Jun 2 11:18:05 AEST 1986


In article <1261 at utcs.uucp> onn at utcs.UUCP (Brian Onn) writes:
>In article <198 at comp.lancs.ac.uk> craig at comp.lancs.ac.uk (Craig Wylie) writes:
>>
>>I surrender  --  is it possible to pass command line arguments to awk?
>>
>>If so - how.  While I'm at it how about doing the same thing to sed.
>>
>>
>>Craig.
>
>The only way I know of to pass command line arguments into awk is by
>defining them as variables in an assign statement on the awk command line, ie
>
>awk -f awkfile arg1=$1 arg2=$2 inputfile
>
>will assign $1 to arg1, and $2 to arg2, inside the body of the awk program. It
>is not possible to assign variable values in this manner to variables that
>are used inside an action associated with the BEGIN pattern.

There is a much more general method to use.  If you put the awk code inside of 
the shell script (rather than using the 'awk -f' option) it can be done as
follows:
-----------------------------------------------------------------------------
#!/bin/csh -f
awk ' {awkvar = '$1'; printf("awkvar: %s, shellvar: %s\n",awkvar,'$1')}'
-----------------------------------------------------------------------------
This program will wait for you to enter a line of input (awk always waits for
this - it is not essential for the program to work - just for awk to work), and
then print out the first argument to the shell twice.  The way that this is done
is by closing the single quotes (') every time you want to access a shell 
variable and then reopening them afterwards.  In the above script the "$1"
refers to the first argument to the shell and not to the first word of the
input line.  This can be done the same way for sed (or any other program for
that matter) because it is not making use of any features of awk but rather
those of the shell - Neil



More information about the Comp.unix mailing list