3

I see there are ways to print lines between two search patterns, as explained here How to grep lines between start and end pattern?

sed -n '/aaa/,/cdn/p' file
awk '/test1/,/test2/'

I need negation of the above, and finding it hard to get the correct command/solution using the standard unix commands grep/sed/awk.

grep -v excludes the lines matching the words, but not all the line between two specific regexs.

Any hints?

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
mtk
  • 27,530
  • 35
  • 94
  • 130

1 Answers1

2

Try

sed '/aaa/,/cdn/d' file

or

awk '/test1/,/test2/{next} {print}'

or (more compactly)

awk '/test1/,/test2/{next} 1'

which prints each record (line) by default, unless it matches /test1/,/test2/ in which case it skips to the next record.

steeldriver
  • 81,074
  • tried the awk solution.. work perfectly. so the {next} block does what exactly? please elaborate – mtk Apr 25 '19 at 12:59
  • @mtk I have added a brief explanation of the awk command – steeldriver Apr 25 '19 at 14:32
  • @mtk The {next} block is needed to work around a limitation / design bug in awk -- the fact the range (/pat1/,/pat2) is not a real expression, and cannot be negated or used in a conditional. That was fixed in perl, where you can do the obvious: perl -ne 'print unless /test1/../test2/' –  Apr 25 '19 at 21:44
  • @mtk the range operator can be negated in sed, so you could also write sed -n '/pat1/,/pat2/!p'. –  Apr 25 '19 at 21:48