Help for search string

Hi all,

I have a file. I want to search particular string in that file and also print next 10 line. I have a code.

 
awk '/search word/{c=10}c&&c--' file name

But I want to pass string as a variable,But my code not working

awk '/$var/{c=10}c&&c--' file name

Please help me
Thanks in advance

Hi,

Try this one,

awk -v n="$var" 'BEGIN{c=0;}/n/{match=1;}{if(macth == 1 && c < 10 ){c++;print;}if( c == 10){match=0;c=0;}}' Input_File

Cheers,
Ranga:)

This is not working

thanks Ranga..
another question came up as I tried to answer this thread:

export cmd="awk '/failed/{ print $0 }' /var/log/dmesg"
exec $cmd

this doesn't work - I got an error in bash shell - how to mask these chars?

exec "$cmd"

1 Like

I can't get the answer. I want to pass search string as a variable

Change macth to match. Then try again.
@rangarasan
Was that a typo?

Hi rangarasan,
When execute your script following error is comming, match syntax error

Are you are using Solaris, use /usr/xpg4/bin/awk instead of awk

by the way using "match" as a name of a variable is not a good idea since it already is the name of an awk function ...

Hi Scrutinizer,
I am not using Solaris , I am using Redhat 5.6

That's right you cannot use match for a variable name..

:slight_smile: my idea is to concatenate the command string and exec it.
in a shell script you maybe can add 'nl' to count rows before and after getting the matching line no print out from that line to no+10..

or you can use grep instead of awk like explained here: grep -n lines before and after