I would like to select the text between two patterns, when some of the patterns can be repeated as follows.
Here is the input:
Blalala
PAT1
'Omfoem From
balanf PAT1 This is the
text that I want
to get PAT2: apples
Whatever: oranges
Here is the output I would like:
This is the
text that I want
to get
I have tried using this script (I am using OSX):
gsed -e 's/PAT1/\nPAT1\n/' -e 's/PAT2/\nPAT2\n/' file1.txt | sed -n '/PAT1/,/PAT2/{//!p;}'
But it outputs the following:
'Omfoem From
balanf
PAT1
This is the
text that I want
to get
In this particular case, I could apply sed -n '/PAT1/,/PAT2/{//!p;}' a second time and I would get the right output.
However, I am looking for a script that works in different situations: if any of the patterns is repeated, independently of the number of times, and if the pattern are not repeated at all.
In any of these cases, I would like to be able to extract the text between pattern PAT1 and PAT2 when PAT1 and PAT2 are the closest to each other.
awkif you want to see some reasonable ways to do this.