Passing Variables to Awk

Hi

I have a unix shell script with an awk statement. I would like to print some of the fields of an input file. However, I would like to print them dynamically, ie by passing the literal $1 $3 into the script to define the output.

I have tried the following:

variable1='$1'
awk -vvar1="$variable1" '/pattern/ {print var1}' file

variable1='$3'
awk -vvar1="$variable1" '/pattern/ {print var1}' file

In the above examples, awk prints the literal $1 or $3, I would like to awk to evaluate the $1 or $3 into the first or third field of the matched pattern.

Is there a way I could do this?

Many thanks
Helen

I'd suggest something like
variable1='1'
awk -vvar1="$variable1" '/pattern/ {print $var1}' file

Cheers
ZB

Hi ZB

That works fine, many thanks for your help.

Cheers
Helen :slight_smile: