1.

How Do I Delete Or Change A Block Of Text If The Block Contains A Certain Regular Expression?

Answer»

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.

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.



Discussion

No Comment Found