How can I make grep print the lines below and above each matching line?

poiuytrez picture poiuytrez · Jul 2, 2009 · Viewed 359.3k times · Source

I have to parse a very large file and I want to use the command grep (or any other tool).

I want to search each log line for the word FAILED, then print the line above and below each matching line, as well as the matching line.

For example:

id : 15
Satus : SUCCESS
Message : no problem

id : 15
Satus : FAILED
Message : connection error

And I need to print:

id : 15
Satus : FAILED
Message : connection error

Answer

pgs picture pgs · Jul 2, 2009

grep's -A 1 option will give you one line after; -B 1 will give you one line before; and -C 1 combines both to give you one line both before and after, -1 does the same.