Issue
I'm working on text files on Linux. I want to be able to print all the lines between two patterns (including the lines where the patterns are found) only if another pattern is found in those lines.
For instance:
PatternStart
line1
line2
PatternInside
line3
line4
PatternEnd
PatternStart
line1
line2
line3
PatternEnd
I want to only get the first block of lines because it contains the PatternInside. Right now, all I can do is extract the lines between my boundary patterns with
awk '/PatternStart/,/PatternEnd/' file
But this will extract the two blocks of lines.
Solution
You can use
awk 'flag{
buf = buf $0 ORS;
if (/PatternEnd/ && buf ~ /PatternInside/)
{printf "%s", buf; flag=0; buf=""}
}
/PatternStart/{buf = $0 ORS; flag=1}' file
Here, the /PatternStart/{buf = $0; flag=1}'
finds the line that matches the PatternStart
pattern, starts writing the output value to buf
, and sets the flag. If the flag is true, subsequent lines are appended to buf
, and once there is a line where PatternEnd
matches and the PatternInside
finds a match in the buf
, the match is printed, buf
gets cleared and the flag is reset.
See the online demo that yields
PatternStart
line1
line2
PatternInside
line3
line4
PatternEnd
Answered By - Wiktor Stribiżew Answer Checked By - Mary Flores (WPSolving Volunteer)