Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
765 views
Welcome To Ask or Share your Answers For Others

1 Answer

This might work for you (GNU sed):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...