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}'
'$' 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.
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.
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With