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

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

This question is related to linux grep

The answer is


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

grep -A 1 -B 1 FAILED file.txt

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
...