1829362 Members
3150 Online
109991 Solutions
New Discussion

Re: Grep issue

 
SOLVED
Go to solution
Mark Misselbrook
Occasional Contributor

Grep issue

I need to grep a string from an output file, but when I get a match I also need the line above and below the matching line i.e

lines read as follows:

----10.70.110.18 PING Statistics----
2 packets transmitted, 1 packets received, 50% packet loss
Mon Jan 17 12:45:49 GMT 2005


HELP!!!!!!!!!!!!!!!!
5 REPLIES 5
John Poff
Honored Contributor

Re: Grep issue

Hi,

If you are on Linux and using the GNU grep, you can use the -B 1 option to print the line before the matching line, and the -C 1 option to print the line after.

JP
Francisco J. Soler
Honored Contributor

Re: Grep issue

Hi Mark, you can do it with awk like this:

awk '/expresion/ {print prev ; print $0 ; getline ; print $0}
{prev=$0}' file_in

If you want, you can create a file like this:
----- file.awk -----
/expresion/ {print prev ; print $0 ; getline ; print $0}
{prev=$0}
-------- end file.awk -----------

Then you can type:

awk -f file.awk file_in

and get the same result.

Frank.
Linux?. Yes, of course.
Sergejs Svitnevs
Honored Contributor
Solution

Re: Grep issue

Mark,

Here is the solution:

cat | sed -n -e '//{x;1!p;g;$!N;p;D;}' -e h

Regards,
Sergejs
Dave Falloon
Trusted Contributor

Re: Grep issue

John was close, the -C 1 gives both the line immediately before and after the matched line.

Here's right out of the gnu grep man page:

OPTIONS
-A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing -- between contiguous groups of matches.
-B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing -- between contiguous groups of matches.
-C NUM, --context=NUM Print NUM lines of output context. Places a line containing -- between contiguous groups of matches.

hope that helps,

--Dave
Clothes make the man, Naked people have little to no effect on society
Mark Misselbrook
Occasional Contributor

Re: Grep issue

The sed solution from Sergejs worked perfectly.

10 points