Passing backslash character to awk variable

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':

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 :

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.

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#

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 :

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.

How about sed?

var='select_id="x_0'  #you need not escape " when using single quote
sed "/$var/,/from/" x.txt

 
1 Like

Thanks msabhi .
I'm using ksh on Solaris. This variation worked.

sed -n -e "/$var/,/from/p" x.txt
1 Like

For reference, awk use of variables. There is no need to escape the double quote:

awk '$0~b,$0~e' b='select_id="x_0' e='from' infile

--
On Solaris, use /usr/xpg4/bin/awk

2 Likes

Your problem in awk was that /sqry/ was looking for a line containing the literal string sqry not the string contained in the variable sqry. To do what you were trying to do in awk, you could have used:

awk -v sqry='select_id="x_0' '$0~sqry,/from/' x.txt

or on Solaris systems:

nawk -v sqry='select_id="x_0' '$0~sqry,/from/' x.txt
2 Likes

print lines between <pattern1> and <pattern2>.

assuming pattren 1 is 'select'
pattern 2 is 'from'

a crude way of printing the lines between pattern1 & pattern2

 
v1=$(grep -n 'select'  x.txt | awk -F ":" '{ print $1}')
v2=$(grep -n 'from' x.txt | awk -F ":" '{ print $2}' )
 
sed -n ' '"$v1"','"$v2"' p' x.txt

it will print lines between pattern1 & pattern2

1 Like