Sed – Deleting Multiline Patterns

Published on Author gryzli

Here is an easy way to delete multiline patterns with sed.

 

Let say we have the following pattern:

 

root@localhost# cat ss.txt

BEGIN
        ID:45
        LS:33
END
BEGIN
        ID:50
        LS:33
END
BEGIN
        ID:47
        LS:33
END
BEGIN
        ID:55
        LS:35
END

 

Now consider we want to delete the BEGIN/END block,  containing “ID:45”:

[gryzli@localhost temp]$ cat ss.txt  | sed -re '/BEGIN/{:a;N;/END/!ba};/ID:47/d'
BEGIN
        ID:45
        LS:33
END
BEGIN
        ID:50
        LS:33
END
BEGIN
        ID:55
        LS:35
END

 

And here is some explanation of the command run above:

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