25

When I type:

echo "foo bar" | gawk -v var="content" '{print $var}'

I expect the output to be content. Why is it foo bar?

4
  • 8
    Try removing $ from $var
    – taliezin
    Jun 21 '16 at 13:17
  • Indeed. I got confused with bash syntax...
    – nicoco
    Jun 21 '16 at 13:30
  • It's a good question and though the answer shows that the $ was misplaced I'm not sure it should be closed as typo. I've seen several of these recently so perhaps we need a canonical one
    – roaima
    Jul 19 '16 at 22:31
  • Didn't find this in time and created a duplicate question by accident.
    – Multisync
    Nov 3 '21 at 18:32
47

Variables are referenced by name as in var, not $var in awk. $n refers to the nth field: $1 for the first field, $2 for the second... or the whole record for n == 0 ($0 is the full record).

Those don't have to be literal numbers. You can use $(1+1) or $variable. If variable contains 1, then $variable will be the first field. A commonly used one is $NF for the last field (NF is the special variable that contains the number of fields).

If, like in your example, the variable doesn't contain a number, that non-number is understood as 0.

So var="content"; print $var, is the same as var=0; print $var, and thus the same as print $0, that is print the whole record.

What you want here is:

echo "foo bar" | gawk -v var="content" '{print var}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.