Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

bash - sed multiline delete with pattern

I want to delete all multiline occurences of a pattern like

  {START-TAG
  foo bar
  ID: 111
  foo bar
  END-TAG}

  {START-TAG
  foo bar
  ID: 222
  foo bar
  END-TAG}

  {START-TAG
  foo bar
  ID: 333
  foo bar
  END-TAG}

I want to delete all portions between START-TAG and END-TAG that contain specific IDs.

So to delete ID: 222 only this would remain:

  {START-TAG
  foo bar 2
  ID: 111
  foo bar 3
  END-TAG}


  {START-TAG
  foo bar 2
  ID: 333
  foo bar 3
  END-TAG}

I have a blacklist of IDs that should be removed.

I assume a quite simple multiline sed regex script would do it. Can anyone help?

It is very similar to Question: sed multiline replace but not the same.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the following:

sed '/{START-TAG/{:a;N;/END-TAG}/!ba};/ID: 222/d' data.txt

Breakdown:

/{START-TAG/ { # Match '{START-TAG'
:a             # Create label a
N              # Read next line into pattern space
/END-TAG}/!    # If not matching 'END-TAG}'...
           ba  # Then goto a
}              # End /{START-TAG/ block
/ID: 222/d     # If pattern space matched 'ID: 222' then delete it. 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...