Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




The sed FAQ
Prev Home Next

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
     /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
           }            #   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:

     1: This will replace the entire block\
     2: with these two lines of text.
The sed FAQ
Prev Home Next

   Reprinted courtesy of Eric Pement. Also available at Design by Interspire