400

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
  • 68,352
  • 105
  • 140
  • 225
poiuytrez
  • 18,348
  • 28
  • 100
  • 156

3 Answers3

809

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,218
  • 15
  • 27
pgs
  • 11,647
  • 2
  • 23
  • 17
56

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,218
  • 15
  • 27
tefozi
  • 4,943
  • 5
  • 36
  • 51
40

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

grep -A 1 -B 1 FAILED file.txt
Milan Babuškov
  • 55,232
  • 47
  • 119
  • 176