Shell Script – Using ‘sed’ to Uncomment Lines Matching a Pattern

sedshell-scripttext processing

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).

Best Answer

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
Related Question