awk variable in regex code example
Example: awk variable in regex
Here comes Mr.Bond
Are you Mr.Holmes
Reconnect with Mr.Maxwell
ending="re"
awk -v pattern="$ending$" '($1 ~ pattern){print $3}'
Returns:
Mr.Bond
Mr.Holmes
How it works:
using awk's -v flag, we created an awk variable, here I named it pattern
it's value depends on a normal shell variable called ending
when evaluated, awk variable pattern is string "re$"
so it's equivalent to: awk '($1 ~ /re$/){print $3}'
note we should surround the pattern with "/" if it's literal
however, we shouldn't do so if using an awk variable
Why don't just write it the literal way?
why use an awk variable at all?
it offers a way to use normal shell variable in awk's regex
in the case abave, imagine ending is dynamic provided by user input
It still works!