Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find lines between two patterns using sed

Tags:

sed

I have the lines in text.txt as below:

blah blah..
blah abc blah..
blah abc blah
blah blah..
blah blah..
blah blah..
blah efg blah blah
blah blah..
blah abc blah
blah abc blah
blah abc blah
blah abc blah
blah abc blah
blah blah..
blah efg blah blah
blah blah..
blah blah..

I want to output the lines between each last occurrence of "abc" before "efg" and "efg", for the above example, I want to output:

blah abc blah
blah blah..
blah blah..
blah blah..
blah efg blah blah
blah abc blah
blah blah..
blah efg blah blah

I know sed can select ranges using two patterns, like:

sed -n '/abc/,/efg/p' test.txt

However the output will begin from the first occurrence of "abc" instead of the last one, the output is as following:

blah abc blah..
blah abc blah
blah blah..
blah blah..
blah blah..
blah efg blah blah
blah abc blah
blah abc blah
blah abc blah
blah abc blah
blah abc blah
blah blah..
blah efg blah blah

Any enhancement can I do on the command line so the output will begin from a last occurrence of "abc"?

like image 766
poiu2000 Avatar asked Jan 15 '13 08:01

poiu2000


1 Answers

This might work for you (GNU sed):

sed -n '/\<abc\>/,/\<efg\>/{/\<abc\>/{h;d};H;/\<efg\>/{x;p}}' file
like image 94
potong Avatar answered Oct 13 '22 04:10

potong