Mohammedz.com

For Linux and Shell scripting.

Delete lines between two matching patterns

2 Comments


Do you want to remove everything in between two matching patterns? Here is a bash script to do that. You can define the patterns in the variables PATRN_START and PATRN_END. The output will be printed to standard output (shell prompt).

You can download the script from here.

~mohammed

Advertisements

2 thoughts on “Delete lines between two matching patterns

  1. Here is a sed one liner to remove lines between two matching patterns.

    sed ‘/PATRN_START/,/PATRN_END/d’ filename.txt
    This will remove all lines in between PATRN_START and PATRN_END, including the matching lines. If the file contains multiple occurrences of PATRN_START and PATRN_END, all of them will be removed.

    sed ‘/PATRN_START/,/PATRN_END/{//p;d;}’
    This is almost similar to the above one, but won’t remove the matching pattern lines (PATRN_START and PATRN_END). All lines in between the matching patterns will be removed.

    ~mohammed

  2. Thanks, I was looking for the non-inclusive example. Here’s one which deletes the lines except the line with the exclude pattern.

    sed ‘/PATRN_START/,/PATRN_END/{/PATRN_EXCLUDE/!d}’

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s