Search code examples
sedtags

How to replace all matched patterns below a matched tag in a file


Let's assume the following file:

blah
blah blah
blah blah blah
string
blah blah blah blah
#####TAG#####
blah blah blah blah
blah blah blah
string
blah blah
string
blah

The goal is to replace all 'string' below the TAG (and only those) with 'another_string' so that the file becomes:

blah
blah blah
blah blah blah
string
blah blah blah blah
#####TAG#####
blah blah blah blah
blah blah blah
another_string
blah blah
another_string
blah

The line numbers of all 'string' cannot be predicted.

Obviously, if I use the basic sed command, all 'string' are replaced:

sed 's|string|another_string|g' file

Any suggestion? I'm open to other tools as well such as perl.


Solution

  • You could use a range address with sed:

    sed '/TAG/,$ { s/string/another_string/g; }' file
    

    The /TAG/,$ part is a range address that starts at the first line matching the regexp TAG and end at the end of the file $. The part between the curly braces is the substitution command that should be applied to all lines that fall within the specified range.