12

I'm using grep in a search that returns significant false-positivies, and it's probably easier for me to identify the good results by inspection, than to write the much more complicated grep expression.

To do that, I need to see more than 1 line for each result.

Can I (How do i) instruct grep to return 1-2 lines above and below each match?

blueberryfields
  • 35,755
  • 24
  • 82
  • 160
  • 3
    For this, and other such queries, 'man grep' is your friend. – Ina Sep 17 '13 at 16:20
  • 1
    What have you tried? What is your grep expression? What are you attempting to search for? – Freddie Sep 17 '13 at 16:20
  • for some reason "man grep" didn't work properly on my machine, but a better choice of google search terms, did. Feel free to close if appropriate – blueberryfields Sep 17 '13 at 18:45
  • @blueberryfields well, you could delete this question. And you could also give an answer providing the solution to your problem – woliveirajr Sep 17 '13 at 18:56
  • Duplicate of http://stackoverflow.com/questions/9081/grep-a-file-but-show-several-surrounding-lines?rq=1, with more info there – Yo Ludke Sep 18 '14 at 12:29

1 Answers1

26

If you have GNU grep, then:

grep -A 2 -B 2 or grep -C 2
-A stands for after
-B stands for before
-C stands for context (both before and after)

Source and more options: http://unixhelp.ed.ac.uk/CGI/man-cgi?grep

Rany Albeg Wein
  • 2,365
  • 2
  • 11
  • 25
ThanksForAllTheFish
  • 6,625
  • 4
  • 32
  • 54