37

Is there a way to comment/uncomment a shell/config/ruby script using command line?

for example:

$ comment 14-18 bla.conf
$ uncomment 14-18 bla.conf

this would add or remove # sign on bla.conf on line 14 to 18. Normally I use sed, but I must know the contents of those lines and then do a find-replace operation, and that would give a wrong result when the there are more than one needle (and we're only want to replace the N-th one).

46

To comment lines 2 through 4 of bla.conf:

sed -i '2,4 s/^/#/' bla.conf

To make the command that you wanted, just put the above into a shell script called comment:

#!/bin/sh
sed -i "$1"' s/^/#/' "$2"

This script is used the same as yours with the exception that the first and last lines are to be separated by a comma rather than a dash. For example:

comment 2,4 bla.conf

An uncomment command can be created analogously.

Advanced feature

sed's line selection is quite powerful. In addition to specifying first and last lines by number, it is also possible to specify them by a regex. So, if you want to command all lines from the one containing foo to the one containing bar, use:

comment '/foo/,/bar/' bla.conf

BSD (OSX) Systems

With BSD sed, the -i option needs an argument even if it is just an empty string. Thus, for example, replace the top command above with:

sed -i '' '2,4 s/^/#/' bla.conf

And, replace the command in the script with:

sed -i '' "$1"' s/^/#/' "$2"
  • 1
    Are the double ' after the -i option intentional? Didn't need them. – raphinesse Mar 26 '15 at 9:50
10

With GNU sed (to replace the files in place with the -i option):

sed -i '14,18 s/^/#/' bla.conf
sed -i '14,18 s/^##*//' bla.conf
2

You can use Vim in Ex mode:

ex -sc 'g/^\s*[^#]/s/^/#/' -cx bla.conf
ex -sc 'g/^\s*#/s/#//' -cx bla.conf
  1. g global regex

  2. s substitute

  3. x save and close

2

You can create a bash_file with functions to reuse it in your projects

#!/bin/bash

# your target file
CONFIG=./config.txt

# comment target
comment() {
  sed -i '' "s/^$1/#$1/" $CONFIG
}

# comment target
uncomment() {
  echo $1
  sed -i '' "s/^#$1/$1/" $CONFIG
}


# Use it so:
uncomment enable_uart
comment arm_freq

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.