ztank1013
ztank1013

Reputation: 7245

grep like command to find matching lines plus neighbourhood lines

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?

Upvotes: 19

Views: 10058

Answers (3)

Kristjan Adojaan
Kristjan Adojaan

Reputation: 537

You can omit -C

grep -2 foo myfile.txt

is equal to

grep -C 2 foo myfile.txt

Upvotes: 7

ennuikiller
ennuikiller

Reputation: 46965

most greps allow the "context" flag making it a bit more readable:

grep --context=3 foo myfile.txt

Upvotes: 18

chotchki
chotchki

Reputation: 4343

Grep itself will do this

grep -A 2 -B 2 foo myfile.txt

Upvotes: 22

Related Questions