4.21. How do I delete or change a block of text if the block contains a certain regular expression?
The following deletes the block between 'start' and 'end'
inclusively, if and only if the block contains the string
'regex'. Written by Russell Davies, with additional comments:
# sed script to delete a block if /regex/ matches inside it
:t
/start/,/end/ { # For each line between these block markers..
/end/!{ # If we are not at the /end/ marker
$!{ # nor the last line of the file,
N; # add the Next line to the pattern space
bt
} # and branch (loop back) to the :t label.
} # This line matches the /end/ marker.
/regex/d; # If /regex/ matches, delete the block.
} # Otherwise, the block will be printed.
#---end of script---
Note: When the script above reaches /regex/, the entire multi-line
block is in the pattern space. To replace items inside the block,
use "s///". To change the entire block, use the 'c' (change)
command:
/regex/c\
1: This will replace the entire block\
2: with these two lines of text.