How to use awk regex as match variable passed from shell

I want to match string stored in a shell variable. So far I have working code

awk '/xyz/{ print "xyz found"} input

What I need is:

str="xyz"
awk '/$str/{ print "xyz found"} input

But it doesn’t work so I searched and found solution:

str="xyz"
awk -v search="$str" '/search/{ print "xyz found"} input

It won’t work either. So how can I match a pattern given in a variable in awk passed from shell?

Try the following to use awk variables in regular expressions:

str="xyz"
awk -v search="$str" '$0 ~ search{ print "xyz found"} input

See our help pages:

Why not:

str=xyz
awk  '/'$str'/ {print $0 }' input

If you close the hyphen before $str and open it again after, the shell reads the value of $str and awk works.

1 Like

Nice. I didn’t know we could do that. It is much simpler than other solution for sure.

1 Like

Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki