6

I'm trying to find a way to comment out a block (multiple lines) in a configuration file. I'd like to match the first line but also act on each line after that.

sed '/\/Some\/Foo\/Bar\/String/' config.file

The following example "code" is what I'm trying to match and comment out. The block will always end with a } but I also know the number of lines after the pattern match so this one would be pattern line + 6.

foo { '/Some/Foo/Bar/String' :
    key1 => value1,
    key2 => value2,
    key3 => value3,
    key4 => value4,
    key5 => value5,
}

Results after sed command

#foo { '/Some/Foo/Bar/String' :
#    key1 => value1,
#    key2 => value2,
#    key3 => value3,
#    key4 => value4,
#    key5 => value5,
#}
6

sed allows us to define ranges of lines and then apply substitutions only within those ranges. We can define a range starting with a line containing Some/Foo/Bar/String and ending with a line containing } and then apply a substitute command to comment out those lines:

$ sed '\|/Some/Foo/Bar/String|,/}/ s/^/#/' file
#foo { '/Some/Foo/Bar/String' :
#    key1 => value1,
#    key2 => value2,
#    key3 => value3,
#    key4 => value4,
#    key5 => value5,
#}

Details

  • \|/Some/Foo/Bar/String|, /}/

    This defines the range. It could have been written as /\/Some\/Foo\/Bar\/String/, /}/ but, to avoid backslashes, I used | as the delimiter in place of / for the first regex.

  • s/^/#/

    This is applied only to lines in the range and it comments them out.

  • Thanks that works great I didn't know sed can define a range then process based on just that range. – LF4 Mar 24 '15 at 16:20
  • Why include the backslash before the first vertical-bar (in \|) but not before the second one (in String|,)? If this is to escape the vertical-bar, why not just choose a delimiter that doesn't need escaping, like "%" or "@" or "!" ? – Kevin Fegan Sep 26 '18 at 3:24
  • @KevinFegan In the pattern \|/Some/Foo/Bar/String|, the delimiter is |. The initial backslash is what tells sed to use | as the delimiter instead of the default /. For more info on the use of standard and nonstandard delimiters when selecting ranges of lines, see Section 4.3 "selecting lines by text matching" of the GNU sed manual – John1024 Sep 26 '18 at 8:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.