awk fails when using variable

This works when I try to execute normally :

echo | format | nawk '/pci@1f,4000/{print x}; {x=$0 }'

But fails when define a variable and put it in a file:

cat test
c=pci@1f,4000
echo | format | nawk "/$c/{print x}; {x=$0 }"

./test
nawk: syntax error at source line 1
 context is
        /pci@1f,4000/{print x}; >>>  {x=. <<< /test }
nawk: illegal statement at source line 1

Any suggestions.

Change as below and try..

$ c="pci@1f,4000"
$ nawk '/c/{print x}; {x=$0 }' 

That doesn't work either.

I thought " " should be used instead of ' ' because when using variables double quotes should be used. Btw.

c=pci@1f,4000
echo | format | nawk "/$c/ {print}"

This works perfectly fine.
And I am using Solaris. "grep -B" isn't working. Any other code?

In the first sample you use single quotes, in the second you use double quotes. Because of these $0 is processed as a shell variable, so you would need to escape that $-sign ( x=\$0 ). Or try:

c=pci@1f,4000
echo | format | nawk -v c="$c" '$0~c{print x} {x=$0 }'

which should work as long as c does not contain special (extended regular expression) characters, in which case they would need to be escaped...

--

There is no need for the double quotes here. /c/ matches the character "c"

2 Likes

Thanks for that code. It worked.

Can you please elaborate where exactly I was going wrong. Thanks.

Hi aksijain, I wrote something in my post, does that help?

Since both the variable and its value contains character c, i was getting the correct result while testing.However i must have verified again the command.