Deano
Deano

Reputation: 12190

sed remove match and next lines

Not sure why my RedGex expression not working, I'm trying to ommit match and next lines

[example.com]
10.0.0.1 
10.0.0.2
[example.net]
10.0.0.10
10.0.0.20

Desired output

[example.net]
10.0.0.10
10.0.0.20

Here is what I have tried so far, but it matches more lines than desired

   sed -e '/(\[example.com\])(.*\n)+/d'

Upvotes: 0

Views: 81

Answers (3)

Ed Morton
Ed Morton

Reputation: 203512

sed is for simple subsitutions on individual lines, that is all. For anything else you should be using awk for every desirable attribute of software (efficiency, clarity, robustness, portability, maintainability, etc., etc.):

$ awk '/^\[/{f=/\[example\.com\]/} f' file
[example.com]
10.0.0.1
10.0.0.2

$ awk '/^\[/{f=/\[example\.com\]/} !f' file
[example.net]
10.0.0.10
10.0.0.20

Upvotes: 1

potong
potong

Reputation: 58420

This might work for you (GNU sed):

sed -n '/^\[[^]*\]/h;G;/\n\[example.com\]/!P;d' file

On encountering a line(s) you don't want to match, store said line in the hold space (HS), append it to the pattern space (PS) and only print current line if the second part does not contain the required string.

Upvotes: 1

Sundeep
Sundeep

Reputation: 23667

I think awk is more suited for this task

$ awk '/\[example.com\]/{f=1; next} /\[example.*\]/{f=0} !f' ip.txt 
[example.net]
10.0.0.10
10.0.0.20
  • /\[example.com\]/{f=1; next} if line matches [example.com] set a flag f and move on to next line
  • /\[example.*\]/{f=0} if line matches \[example.*\], unset the flag
  • !f print lines if flag is not set


With sed, the best I could do is using this answer

$ sed '/\[example.com\]/,/\[example.*\]/ { /\[example.com\]/d; /\[example.*\]/!d }' ip.txt 
[example.net]
10.0.0.10
10.0.0.20

Upvotes: 2

Related Questions