486

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
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
poiuytrez
  • 21,330
  • 35
  • 113
  • 172

3 Answers3

952

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,619
  • 1
  • 19
  • 30
pgs
  • 13,385
  • 2
  • 25
  • 17
69

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,619
  • 1
  • 19
  • 30
tefozi
  • 5,390
  • 5
  • 38
  • 52
50

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

grep -A 1 -B 1 FAILED file.txt
Milan Babuškov
  • 59,775
  • 49
  • 126
  • 179