Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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!

Thanks!

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

share|improve this question

2 Answers 2

up vote 3 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
1  
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

 
discard

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.