Reputation: 986
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
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
Reputation: 61046
{ 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 }
Upvotes: 2