Karol Lewandowski
Karol Lewandowski

Reputation: 986

Filter text between two patterns with preceding n lines

Assume, that we have a file like this:

l1 abcdefgh
l2 abcde
l3 some line i want to retrieve
l4 another line i want to retrieve
l5 matching pattern
l6 abc
l7 abcdef
l8 unmatching pattern
l9 blah blah

I want to retrieve the following output:

l3 some line i want to retrieve
l4 another line i want to retrieve
l5 matching pattern
l6 abc
l7 abcdef

So I want to output two lines before first occurence of matching pattern, matching line and all lines until I hit 'unmatching pattern'. Of course there can be more than one text range to retrieve.

What is the easiest way to achieve that? Which tools should I use? What to google about? Learning awk from basics is not possible at this moment.

Upvotes: 1

Views: 956

Answers (3)

Beta
Beta

Reputation: 99134

In sed:

sed -n '1N;N;/pattern/{N;N;p;s/.*//;N;N;};$!D' filename

Upvotes: 1

kurumi
kurumi

Reputation: 25609

awk '/pattern/{print p"\n"q"\n"$0;f=1;next} {p=q;q=$0} f{s=s"\n"$0; if ($0~/unmatching/) { print s;exit} }' file

Upvotes: 2

Dr. belisarius
Dr. belisarius

Reputation: 61046

In awk

{ a[i++ % 3 ]=$0} 
/ matching pattern/ {print a[(i-3)%3];print a[(i-2)%3];i=0}
/matching pattern/,/unmatching pattern/ {if($0 !~ /unmatching pattern/) print }

Working here

Upvotes: 2

Related Questions