Quantcast
Channel: UNIX and Linux Forums
Viewing all articles
Browse latest Browse all 16232

Passing backslash character to awk variable

$
0
0
Hi All.
I have a file that contains some special characters and I'm trying to use AWK to search for lines between <pattern1> and <pattern2>.
As an example:
I need the lines between the line containing ' select_id="x_0 ' and the line containing the next instance of ' from '. This is a file called 'x.txt':

Code:

blah
set $a x_0 $b
blah (
q_db_task=1000, select_id="x_0", text=" select ",
blah=rec (
table="green", text="min(blue)", text="max(brown)",
text="sum(green.PURPLE)"
text="sum(green.BLACK)", text="sum(green.YELLOW)",
zed_var="$d MYCALC1SUM"
text="sum(green.PINK)",
)
from=" from ",
tablist="green", where="
blah
zed_var="$G 1", text="
blah
)
blah
from=" from",
blah

If I use the following then I get the output I need :
Code:

awk  '/select_id=\"x_0/,/from/' x.txt
(with the double quote escaped.)
However - the first search pattern might change so I need to pass that to awk as a variable.
E.G.
Code:

srvr# awk -v sqry='select_id=\\"x_0' '/sqry/,/from/' x.txt
awk: syntax error near line 1
awk: bailing out near line 1
and same using nawk returns nothing.
srvr# nawk -v sqry='select_id=\\"x_0' '/sqry/,/from/' x.txt
srvr#

But this works to match the first pattern using similar syntax.

srvr#
Code:

nawk -v sqry='select_id=\\"x_0' '$0 ~ sqry' x.txt
q_db_task=1000, select_id="x_0", text=" select ",

I think I fixed it using awk in a script :
Code:

BEGIN {awkvar2=sqry;awkvar3="from"}

($0 ~ awkvar2),($0 ~ awkvar3)

BUT - Any help to understand why the pattern match doesn't work would be much appreciated.

Viewing all articles
Browse latest Browse all 16232

Trending Articles