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

LinuxGrep

Linux Problem Overview


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

Linux Solutions


Solution 1 - Linux

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.

Solution 2 - Linux

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

Solution 3 - Linux

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

grep -A 1 -B 1 FAILED file.txt

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpoiuytrezView Question on Stackoverflow
Solution 1 - LinuxpgsView Answer on Stackoverflow
Solution 2 - LinuxtefoziView Answer on Stackoverflow
Solution 3 - LinuxMilan BabuškovView Answer on Stackoverflow