awk regex variable code example

Example: awk variable in regex

# you should probably store regex pattern in an awk variable

# say we have the following 3 lines to to dealt by awk
Here comes Mr.Bond
Are you Mr.Holmes
Reconnect with Mr.Maxwell

# find the name, if the first word ends with "re"

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!

Tags:

Misc Example