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?

1 Answer 1

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.

4
  • tried the awk solution.. work perfectly. so the {next} block does what exactly? please elaborate
    – mtk
    Apr 25, 2019 at 12:59
  • @mtk I have added a brief explanation of the awk command Apr 25, 2019 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/'
    – user313992
    Apr 25, 2019 at 21:44
  • @mtk the range operator can be negated in sed, so you could also write sed -n '/pat1/,/pat2/!p'.
    – user313992
    Apr 25, 2019 at 21:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .