Use bash variable in AWK expression

Instead of quoting games in the shell, use the -v option to pass the shell variable as an awk variable:

awk -v ref="$REF" 'match($0, ref) {print $2}'

If $REF is just text and not a regular expression, use the index() function instead of match().


You question is worded really poor...

Anyway, I think you want this:

REF=SEARCH_TEXT
echo "some text" | awk "/$REF/{print \$2}"

Note the escaping of $2 and the double quotes.

or this:

REF=SEARCH_TEXT
echo "some text" | awk "/$REF/"'{print $2}'

Note the judicious use of double and single quotes and no escaping on $2.

You have to use shell expansion, as otherwise it would encompass exporting a shell variable and using it from the environment with awk - which is overkill in this situation:

export REF=SEARCH_TEXT
echo "some text" | awk '{if (match($0, ENVIRON["REF"])) print $2}'

I think awk does not support variables in /.../ guards. Please correct me if I'm wrong.


In gawk, you have the ENVIRON array, e.g. awk 'END{print ENVIRON["REF"]}' /dev/null will print your variable if you've exported it out from the shell to sub-processes.