0

Say we got an example file:

11
12
ss
dd
gg
32
ss
dd
gg

So i want to remove the block which meet the pattern ss gg, but i want to keep the start pattern ss

The out put should be

11
12
ss
32
ss

Using this code

awk '/ss/,/gg/{next}1' file 

It also excludes the start pattern ss. How could we keep it?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
user2669497
  • 157
  • 2
  • 11

2 Answers2

3

I would use a printing flag like this:

$ awk '!flag; /ss/ {flag=1} /gg/ {flag=0}' file
11
12
ss
32
ss

This uses a similar logic as How to select lines between two marker patterns which may occur multiple times with awk/sed, moving the flag in a way that makes the start pattern to be printed.

  • !flag since the default value of a variable is 0, negating it makes it true. This way, we have a default True value, which triggers awks default action: print $0.
  • /ss/ {flag=1} sets the flag when the text ss is found.
  • /gg/ {flag=0} unsets the flag when the text gg is found.
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
3

Using sed you can do:

sed '/ss/,/gg/{/ss/!d;}' file
11
12
ss
32
ss

This sed deletes all lines from pattern ss to gg except when line is ss using !d command.

anubhava
  • 761,203
  • 64
  • 569
  • 643