Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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. :/

share|improve this question
up vote 4 down vote accepted

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
share|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
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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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