Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk - Variable expansion in regex

Tags:

regex

awk

Why doesn't something like this work:

echo 4 | awk --assign=abc=4 '/$abc/'

The actual example is much more complicated. Basically I have a regex I need repeated several times so I'm storing it in abc. Is there any way to expand an awk variable in /<regex>/? I've tried single and double quotes, every combination. I really need that line to be single quoted because I have several double quotes, it actually looks more like awk --assign=test=something '/$test/ { a lot of stuff here inc $test several times with double quotes; }'

like image 385
user2672807 Avatar asked Feb 02 '26 21:02

user2672807


1 Answers

awk doesn't use variables between / and / regex:

Following equivalent will work with same effect using ~ regex operator:

echo 4 | awk --assign=abc=4 '$0 ~ abc'
4
like image 191
anubhava Avatar answered Feb 04 '26 14:02

anubhava