poiu2000
poiu2000

Reputation: 980

find lines between two patterns using 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"?

Upvotes: 7

Views: 4266

Answers (1)

potong
potong

Reputation: 58351

This might work for you (GNU sed):

sed -n '/\<abc\>/,/\<efg\>/{/\<abc\>/{h;d};H;/\<efg\>/{x;p}}' file

Upvotes: 6

Related Questions