If we want to get the text between the 2 patterns excluding themselves.
Supppose we have the file test.txt containing :
blabla blabla foo here is the text to keep between the 2 patterns bar blabla blabla The following code can be used :
sed -n '/foo/{ n b gotoloop :loop N :gotoloop /bar/!{ h b loop } /bar/{ g p } }' test.txt For the following output :
here is the text to keep between the 2 patterns How does it work, let's make it step by step
/foo/{is triggered when line contains "foo"nreplace the pattern space with next line, i.e. the word "here"b gotoloopbranch to the label "gotoloop":gotoloopdefines the label "gotoloop"/bar/!{if the pattern doesn't contain "bar"hreplace the hold space with pattern, so "here" is saved in the hold spaceb loopbranch to the label "loop":loopdefines the label "loop"Nappends the pattern to the hold space.
Now hold space contains :
"here"
"is the":gotoloopWe are now at step 4, and loop until a line contains "bar"/bar/loop is finished, "bar" has been found, it's the pattern spacegpattern space is replaced with hold space that contains all the lines between "foo" and "bar" that have saved during the main looppcopy pattern space to standard output
Done ?!