430

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
Samuel Liew
  • 72,637
  • 105
  • 156
  • 238
poiuytrez
  • 19,824
  • 31
  • 105
  • 161

3 Answers3

871

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.

webaholik
  • 1,400
  • 15
  • 29
pgs
  • 12,327
  • 2
  • 24
  • 17
61

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
...
webaholik
  • 1,400
  • 15
  • 29
tefozi
  • 5,185
  • 5
  • 37
  • 52
43

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

grep -A 1 -B 1 FAILED file.txt
Milan Babuškov
  • 57,554
  • 49
  • 122
  • 178