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

Viewed 426241

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


Input:

id : 15
Status : SUCCESS
Message : no problem

id : 15
Status : FAILED
Message : connection error

Desired output for grep 'FAILED':

id : 15
Status : FAILED
Message : connection error
3 Answers

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.

Use -B, -A or -C option

grep --help
...
-B, --before-context=NUM  print NUM lines of leading context
-A, --after-context=NUM   print NUM lines of trailing context
-C, --context=NUM         print NUM lines of output context
-NUM                      same as --context=NUM
...

Use -A and -B switches (mean lines-after and lines-before):

grep -A 1 -B 1 FAILED file.txt
Related