Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed multiline delete with pattern

Tags:

bash

sed

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.

like image 344
Bastl Avatar asked Jun 07 '16 13:06

Bastl


People also ask

How do you delete a pattern in the file using sed?

Just like in VIM, we will be using the d command to delete specific pattern space with SED. To begin with, if you want to delete a line containing the keyword, you would run sed as shown below. Similarly, you could run the sed command with option -n and negated p , (! p) command.

How do you delete a line with a pattern in Linux?

Delete lines based on patternSed can search for a particular pattern and perform the specified actions on the line. We can use this feature to delete specific lines that match a pattern. Let's have a look at the following demonstration. Sed will remove any line that contains the string “the”.

How do you put multiple patterns in sed?

Use multiple patterns at once with SedLook out for the semicolon(;) to add more patterns within the single command.

How do I remove a specific pattern from a Unix file?

N command reads the next line in the pattern space. d deletes the entire pattern space which contains the current and the next line. Using the substitution command s, we delete from the newline character till the end, which effective deletes the next line after the line containing the pattern Unix.


1 Answers

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. 
like image 157
Andreas Louv Avatar answered Oct 12 '22 15:10

Andreas Louv