3

I'm trying to uncomment certain lines of a file, the comments start with an option that gets followed by 1 or more lines of comments. Here's a minimal example of file I'm trying to process (example.txt):

# Ignore this one
# first-option)
#   something-something x \
#       run-something-else y \
#       run-after-this z \
#       set-some-config-var 10 10

# Uncomment this one
# second-option)
#   something x \
#       run-something-else y \
#       run-something-else-again z \
#       run-after-this-something z \
#       set-some-config-var 10 10 \
#       set-some-config-var cool

and my naive solution (test.sed), by first finding the desired pattern, then applying repeated substitutions:

#!/usr/bin/env sed

/#.*second-option/{
    s/# //; p; n;
    s/# //; p; n;
    s/# //; p; n;
    s/# //; p; n;
    s/# //; p; n;
    s/# //; p; n;
    s/# //; p; n;
}

output:

$ sed -n -f test.sed example.txt
second-option)
  something x \
      run-something-else y \
      run-something-else-again z \
      run-after-this-something z \
      set-some-config-var 10 10 \
      set-some-config-var cool

I'm not well versed in all of seds options, but got curious if there's a more generic way of doing this (or less verbose one).

3

I would do this using an address range. We want to start when we see second-option and end when we see a blank line:

#!/bin/sed -f

/^#.*second-option/,/^#? *$/s/^# //
#     from         |  to   | substitute
1
  • Thanks for this solution!
    – Aristu
    Oct 4 '19 at 15:23
1
$ sed -e '
    /^#[[:blank:]]*second-option[)]$/!b
    :a;$!N;s/\\$/&/;ta
    s/\(\n\)#/\1/g;s/^#//
  ' file

On a bash command line in Posix sed

Or the following with Gnu sed:

 $ sed -e '/^#\s*second-option[)]$/,/[^\]$/s/^#//' file
1
  • Thanks for this solution as well!
    – Aristu
    Oct 4 '19 at 15:25

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.