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,
#}
0

1 Answer 1

8

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.

3
  • Thanks that works great I didn't know sed can define a range then process based on just that range.
    – krizzo
    Commented Mar 24, 2015 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 "!" ? Commented Sep 26, 2018 at 3:24
  • 1
    @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
    Commented Sep 26, 2018 at 8:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .