3

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

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

5 Comments

It's strange seeing the long option used.
Thanks. I did some research in the gawk manual but I didn't see anything about no variables in //. @sudo_O yeah I tried long after short didn't work (I thought maybe there was a difference). I switched back to -v with the answer provided.
They is not difference, just in the 500+ awk questions I have answered I've never seen it used. I had to actually check the man myself!
I find the gawk manual pretty hard to navigate. Nevertheless I found gnu.org/software/gawk/manual/html_node/… and gnu.org/software/gawk/manual/html_node/Computed-Regexps.html
@glennjackman: Thanks for sharing that link (I couldn't trace that in my search).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.