Languages and Scripting
cancel
Showing results for 
Search instead for 
Did you mean: 

need to pass in variable as regular expression in awk

need to pass in variable as regular expression in awk

How do I pass in a variable as a search pattern in my awk statement?

I have a line read from a file and I am trying to use that line as an expression in awk. It breaks down like this:

cat locks.tmp | while read LINE
do

awk '/spid/{x=1;y=0}/$LINE/ {if (y>3){l[y]="\n"; while(i++
I have tried using -v line=$LINE and then /.../.../line/ but it's not working...

The line looks like :
TYES Lock => Oct 23, 2004 00:14:45 - te_tyesp04_20 - 64

Anyone have any ideas???
5 REPLIES
Geoff Wild
Honored Contributor

Re: need to pass in variable as regular expression in awk

What if you put the $LINE in single quotes?

/'$LINE'


IMHO - this would be better in perl - but I'm far from a perl guru - maybe Merijn can help you out :)

Rgds...Geoff
Proverbs 3:5,6 Trust in the Lord with all your heart and lean not on your own understanding; in all your ways acknowledge him, and he will make all your paths straight.
Highlighted

Re: need to pass in variable as regular expression in awk

I think if I put it in single quotes the first one would end the one outside my awk...

awk '/...... / '$LINE.....
Geoff Wild
Honored Contributor

Re: need to pass in variable as regular expression in awk

okay, would this work?

/\\/'$LINE$'\\//

I think it's just a matter of finding the right number of escapes...

Rgds...Geoff
Proverbs 3:5,6 Trust in the Lord with all your heart and lean not on your own understanding; in all your ways acknowledge him, and he will make all your paths straight.

Re: need to pass in variable as regular expression in awk

I think you're right... but interestingly if I hardcode the LINE value...

awk -v line="TYES Lock => Oct 23, 2004 10:12:57 - te_tyesp05_25 - 146" '/spid/{x=1;y=0}/line/ {if (y>3){l[y]="\n"; while(i++
using it with -v doesn't work but if I don't use the -v...

awk '/spid/{x=1;y=0}/TYES Lock => Oct 23, 2004 10:12:57 - te_tyesp05_25 - 146" '/spid/{x=1;y=0}/line/ {if (y>3){l[y]="\n"; while(i++
I get what I'm looking for...
I just need a way to use the $LINE variable in my regular expression....

Re: need to pass in variable as regular expression in awk

Correction.. the last part should look like this:

awk '/spid/{x=1;y=0}/TYES Lock => Oct 23, 2004 10:12:57 - te_tyesp05_25 - 146/ {if (y>3){l[y]="\n"; while(i++
It also doesn't like it if I put the actual LINE in quotes...

awk '/spid/{x=1;y=0}/"TYES Lock => Oct 23, 2004 10:12:57 - te_tyesp05_25 - 146"/ {if (y>3){l[y]="\n"; while(i++
Wonder why the line variable doesn't work??