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:
https://www.cyberciti.biz/faq/linux-unix-appleosx-bsd-bash-passing-variables-to-awk/

1 Like

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.

2 Likes

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

1 Like

I tried to get total lines from a pattern to the end of file. And, it seems like for this lines it worked out ok:

$ t=2023-10-04T10; sudo awk -v var="$t" '/'$t'/,0' file.log | wc -l
6819
$ t=2023-10-04T11; sudo awk -v var="$t" '/'$t'/,0' file.log | wc -l
2290

Unfortunately, when I put it into a script or make a one-line command with a similar expression that has variables, I only get un zero:

$ m=100; mm=$(date -u +'%FT%R' -d ''$m' minutes ago'); echo `date -u +'%FT%R'`; echo $mm; sudo awk -v var="$mm" '/'$mm'/,0' file.log | wc -l
2023-10-04T12:56
2023-10-04T11:16
0

What I missed with this? Thanks!

Answering to myself, I have to admit a mistake about the nonexistence pattern (calculated by time) in a log file I tried to find in it. Anyway, I hope this example could be helpful to someone.