Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed - extract STRING between first occurrence of MATCH1 and next occurrence of MATCH2

Tags:

regex

bash

sed

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?

like image 780
lecodesportif Avatar asked Dec 08 '10 20:12

lecodesportif


1 Answers

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.

like image 68
Dennis Williamson Avatar answered Sep 30 '22 13:09

Dennis Williamson