Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use bash variable in AWK expression

I tried the following snippet in a shell script but awk didn't find $REF

REF=SEARCH_TEXT
echo "some text" | awk '/$REF/{print $2}'
like image 829
vehomzzz Avatar asked Dec 23 '10 14:12

vehomzzz


People also ask

How do I use shell variables in an awk script?

'$' symbol is used with a shell variable name to read the value. The second command reads the variable, $myval with a single quote(') and the third command reads the variable $myvar with double quote(“) in the `awk` statement.

How do you pass external variables to awk?

In the preceding method, variables are specified as key-value pairs, separated by a space, and (v1=$var1 v2=$var2 ) as command arguments to awk soon after the BEGIN , { } , and END ... Get Linux Shell Scripting Cookbook - Third Edition now with the O'Reilly learning platform.

How do you pass command line arguments in awk?

Arguments given at the end of the command line to awk are generally taken as filenames that the awk script will read from. To set a variable on the command line, use -v variable=value , e.g. This would enable you to use num as a variable in your script. The initial value of the variable will be 10 in the above example.


1 Answers

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().

like image 136
glenn jackman Avatar answered Sep 24 '22 08:09

glenn jackman