1

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?

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.