Find lines between two patterns using sed

I have lines in text.txt as shown 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 print lines between each last occurrence of "abc" before "efg" and "efg", for the above example I want to print:

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

I know that sed can select ranges using two patterns, for example:

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

However, the output will begin with the first appearance of "abc" instead of the last, the output is as follows:

 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 improvements can be made on the command line so that the output starts with the last occurrence of "abc"?

+7
source share
1 answer

This may work for you (GNU sed):

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

All Articles