Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print lines between patterns with awk

Tags:

awk

Going back to this discussion: Print all lines between two patterns, exclusive, first instance only (in sed, AWK or Perl)

The proposed solution fails once the ending pattern is a substring of the start pattern.

Example input:

aaa
PATTERNSTART
bbb
ccc
ddd
PATT
eee

Produces output failure:

awk '/PATT/{exit} f; /PATTERNSTART/{f=1}' dat

Gives empty return instead of expected

bbb
ccc
ddd

Corner cases:

  • If start pattern is not found nothing shall be done
  • If ending pattern is not encountered print from start pattern to end of file
  • Only first occurrence of start / end pattern pair to be considered

Not sure I found all corner cases. Corner cases beyond above might be treated canonically . Thanks.

like image 560
Gert Gottschalk Avatar asked May 07 '26 12:05

Gert Gottschalk


2 Answers

You must use regex start and end anchors to avoid matching partial patterns:

awk 'f && /^PATT$/{exit} f; /^PATTERNSTART$/{f=1}' dat

bbb
ccc
ddd

or else use string comparison and avoid regex altogether:

awk 'f && $0 == "PATT"{exit} f; $0 == "PATTERNSTART"{f=1}' dat
like image 78
anubhava Avatar answered May 10 '26 18:05

anubhava


Make sure you use anchors:

$ awk '/^PATT$/{exit};/^PATTERNSTART$/{f=1;next}; {if (f){print}}' file
bbb
ccc
ddd
like image 23
Paolo Avatar answered May 10 '26 19:05

Paolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!