Using bash variables in awk

While there seems nothing wrong with this:

sign="--"
awk '{if ($1 == $sign ) print $1 }'

..it doesn’t give the intended result. To be able to use bash variables in awk, you first need to assign the variables with the -v option:

sign="--"
awk -v sign="$sign" '{if ($1 == sign ) print $1 }'

From the awk man page:

The option -v followed by var=value is an assignment to be done before (the awk) prog is  executed;  any  number  of  -v  options  may be present.

One Response to “Using bash variables in awk”

  1. Marc says:

    Good tip. I recall having to use this a while back and it took me a while to find it.

    Though I suspect that when you’re having to do stuff like this, it’s probably a pretty good sign that your shell script is getting too complicated and it should probably be done in something like Perl.