I want to display three or four lines before and after a certain string in a really huge file, which I can' topen with vi. How is this done?

I tryed

grep -i -n -r 'mysearchstring'

but this only gives me one line. I need some lines before and after to get the context!


I once have seen a terminal command, that does that, but I forgot and I can't find it again. :/


Use grep with the -A (how many lines to display after the match) and -B (how man lines to display before the match) parameters:

grep -i -n -r -A 4 -B 4 'mysearchstring' file.xml
| improve this answer | |
  • Thank you, I overlooked this option while reading the man page myself. But found it later on. ;-) Please complete your example, so that it shows how to search within a given file, and I will be glad to accept your answer. =) – Aufwind May 30 '11 at 20:30
  • 2
    I would suggest that -A4 -B4 could be shortened with -C4. – enzotib May 30 '11 at 20:39

I got it:

grep -n -A 5 -B 5 'searchstring' file.xml

This finds searchstring in file.xml and display 5 lines trailing and 5 leading lines.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.