Search code examples
linuxpcre

Remove lines from a file between lines matching a pattern


If this is my file:

This part can stay
START ALPHA
This should be deleted
And this too
END ALPHA
This should stay
START BETA
This should be deleted
END BETA
This should stay

Everything between the "START (whatever)" and "END (whatever)" lines should be deleted.

How can I do this? I'm can use sed, perl, python, whatever works.


Solution

  • use an ed(1) or sed(1) script:

    $ cat filter.sh
    #!/bin/sh
    exec sed "/START $1/,/END $1/d" data.txt
    $ filter.sh ALPHA
    This part can stay
    This should stay
    START BETA
    This should be deleted
    END BETA
    This should stay
    $ filter.sh BETA
    This part can stay
    START ALPHA
    This should be deleted
    And this too
    END ALPHA
    This should stay
    This should stay
    $ _
    

    the $ sign is the shell prompt, I think you'll understand. filter.sh is the script that does what you want.