Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep like command to find matching lines plus neighbourhood lines

Tags:

grep

bash

grep command is really powerful and I use it a lot.

Sometime I have the necessity to find something with grep looking inside many many files to find the string I barely remember helping myself with -i (ignore case) option, -r (recursive) and also -v (exclude).

But what I really need is to have a special output from grep which highlight the matching line(s) plus the neighbourhood lines (given the matching line I'd like to see, let's say, the 2 preceding and the 2 subsequent lines).

Is there a way to get this result using bash?

like image 906
ztank1013 Avatar asked Sep 11 '11 21:09

ztank1013


People also ask

How do you grep with surrounding lines?

For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. If you want the same number of lines before and after you can use -C num . This will show 3 lines before and 3 lines after.

How do you grep multiple lines after a match?

Use the -A argument to grep to specify how many lines beyond the match to output. And use -B n to grep lines before the match. And -C in grep to add lines both above and below the match!

Can grep match multiple lines?

grep is a command line text searching utility that is able to find patterns and strings in files and other types of input. Most matches will match on one line only, but it's often useful to match across multiple new lines.


1 Answers

Grep itself will do this

grep -A 2 -B 2 foo myfile.txt
like image 113
chotchki Avatar answered Sep 22 '22 19:09

chotchki