Skip to content
Advertisement

Select first match between two patterns.Restart search if a 3rd pattern is found using sed/awk/grep

I am struggling with the following task(I’ve been searching for answer for a while).

The search is for text between START_PATTERN and END_PATTERN1

Having a file structured like this:

text
text
...
START_PATTERN
line1
line2
END_PATTERN2
text
text
...
START_PATTERN
line1
line2
END_PATTERN1
text
text
...

The task would be to restart search if END_PATTERN2 is found. Thus the command output should be:

START_PATTERN
line1
line2
END_PATTERN1

Thank you for your time!

Advertisement

Answer

this line should work for your example:

 tac file|sed '/END_PATTERN1/,/START_PAT/!d'|tac

test: (I added xx to the expected block lines):

kent$  cat f
text
text
...
START_PATTERN
line1
line2
END_PATTERN2
text
text
...
START_PATTERN
xxline1
xxline2
END_PATTERN1
text


kent$  tac f|sed '/END_PATTERN1/,/START_PAT/!d'|tac
START_PATTERN
xxline1
xxline2
END_PATTERN1

Edit

take only the first match, with awk only:

awk '{a[NR]=$0}
     /START_PAT/{s=NR}
     /END_PATTERN2/{s=0}
     /END_PATTERN1/{exit}
     END{for(i=s;i<=NR;i++)print a[i]}' file
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement