Skip to main content
edited tags
Link
Lauren
  • 2.7k
  • 2
  • 18
  • 9
Source Link
Lauren
  • 2.7k
  • 2
  • 18
  • 9

Variable Substitution in Awk Print Statement -v

I've spent over an hour poking at this. It can't be this hard... I want to print a column of data from one file to another file. The column I want to print is dependent on what is passed in and stuff happening earlier in the script, but it is called COL. The file I need to pull the information from is called $1.db, $1 being the first argument passed in (already checked that it exists). What I have currently:

awk -v colvar="$COL" '{ print $colvar }' "$1.db"  >> tmp2.tmp

This results in the entire contents of $1.db being printed to tmp2.tmp, not just the column.

When I sh -xv it, I see

awk -v colvar="$COL" '{ print $colvar }' "$1.db"  >> tmp2.tmp
+ awk -v colvar=3 '{ print $colvar }' cop4342.db

So, I see that the awk var is being set to the value of COL, but it isn't being substituted inside the print statement. I suspect that is due to the single quotes, but don't know what to do about it. Any help appreciated : )