Use bash variable in AWK expression

限于喜欢 提交于 2019-12-04 19:12:30

问题


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}'

回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/4519408/use-bash-variable-in-awk-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!