Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question
1  
There is an A to this Q titled: Uncommenting multiple lines of code, specified by line numbers, using vi or vim which shows many methods for doing this using sed, perl, etc. Specifically the A by terdon! –  slm May 9 at 3:24

2 Answers 2

up vote 12 down vote accepted

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
share|improve this answer

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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