Andrew
Andrew

Reputation: 247

Grep ignore multiple lines

Is there a way with Grep to use the -v switch to ignore a line and the next number of lines after it. Its basically to filter exceptions from a log file i.e.

Valid log entry 1
Exception exceptionname
    at a.b.c
    at d.e.f
    ...
Valid log entry 2

grep it to produce :

Valid log entry 1
Valid log entry 2

I have tried grep -v Exception -A 2

but this doesn't work.

Any ideas would be appreciated.

Upvotes: 15

Views: 7846

Answers (4)

RafDouglas C. Tommasi
RafDouglas C. Tommasi

Reputation: 156

Improving on glenn jackman's, by piping some commands you can get the before/after behaivour:

awk -v nlines_after=5 '/EXCEPTION/ {for (i=0; i<nlines_after; i++) {getline};print "EXCEPTION" ;next} 1' filename.txt|\
tac|\
awk -v nlines_before=1 '/EXCEPTION/ {for (i=0; i<nlines_before; i++) {getline}; next} 1'|\
tac

Upvotes: 0

Idelic
Idelic

Reputation: 15572

sed -n '/^Exception/,+2!p' filename

Upvotes: 7

glenn jackman
glenn jackman

Reputation: 246744

Try awk:

awk -v nlines=2 '/^Exception/ {for (i=0; i<nlines; i++) {getline}; next} 1'

Upvotes: 11

Adam Batkin
Adam Batkin

Reputation: 52964

In your case, you might tell grep to also ignore any lines that contain leading whitespace:

grep -v 'Exception|^\s'

Upvotes: 3

Related Questions