Operating System - HP-UX
1834137 Members
2465 Online
110064 Solutions
New Discussion

concatenating variables and regexp in awk

 
SOLVED
Go to solution
Michele (Mike) Alberton
Regular Advisor

concatenating variables and regexp in awk

Hi Folks !

I was trying to find a way to use awk to extract patterns made of some regexp and a variable.

Basically I should invoke:

awk -v VALUE="whatever" -f *.awk xxx.dat

and I would like to extract for instance:

+whatever
whatever123
...
Do you know how to concatenate for instance
/\+?/ with a variable ?

Thanks !

Mike
3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: concatenating variables and regexp in awk

Here is one approach:

awk -v VALUE="whatever" '{ if ($0 ~ VALUE) print $0 }' xxx.dat

That should work for your trivial example but if you need more powerful regular expressions then you might have to use a BEGIN { } section leveraging a sprintf to build up a variable for the subsequent match (~) operator within the main awk loop.
If it ain't broke, I can fix that.
Graham Cameron_1
Honored Contributor

Re: concatenating variables and regexp in awk

123 is easy.
Build up your regexp in the BEGIN clause.
The space operator concatenates 2 strings, so the following will print any line containing "whatever123":

awk -v VALUE=whatever '
BEGIN {yourregexp=VALUE "123"}
$0 ~ yourregexp {print}
' xxx.dat

+ is more difficult, because it has special meaning in an RE.
You could use index:

awk -v VALUE=whatever '
BEGIN {yourregexp="+" VALUE}
{if (index ($0, yourregexp) != 0) print }
' xxx.dat

- Graham
Computers make it easier to do a lot of things, but most of the things they make it easier to do don't need to be done.
Michele (Mike) Alberton
Regular Advisor

Re: concatenating variables and regexp in awk

Thank You guys, points well earned...

I love this Forum.

Cheers,

Mike