Using sed
, I would like to extract STRING between the first occurrence of MATCH1
and the next occurrence of MATCH2
.
echo "abcd MATCH1 STRING MATCH2 efgh MATCH1 ijk MATCH2 MATCH2 lmnop MATCH1" | sed...
I tried this in various ways, but given that MATCH1
and MATCH2
both may appear several times in a row, it has turned out difficult to extract STRING. Any idea how I can achieve this result?
These only return the string between the matches and work even if MATCH1 == MATCH2
.
echo ... | grep -Po '^.*?\K(?<=MATCH1).*?(?=MATCH2)'
Here's a sed
solution:
echo ... | sed 's/MATCH1/&\n/;s/.*\n//;s/MATCH2/\n&/;s/\n.*//'
The advantage of these compared to some of the other solutions is that each one consists of only one call to a single utility.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With