up vote 0 down vote favorite
share [g+] share [fb]

Anyone know if it's possible in vi to replace only uncommented/non-blank lines with comments?

If I want to replace a commented line with something I know I can use :%s/^#/##foo##/g -- but I am looking for the opposite of this.

Example file:

# Some user's cron

# Test comments
00 00 * * * ~/somescript.sh

Expected result:

# Some user's cron

# Test comments
##DISABLE##00 00 * * * ~/somescript.sh

Thanks in advance, sitnam

link|improve this question
feedback

7 Answers

:g/^[0-9\*]/s/^/##DISABLED##/

This "g/RE/" part selects all lines that begin with a number or the * character. The "s/RE/replacement/" then does the work on all selected lines.

link|improve this answer
or :g/^[^#]/s/^/##DISABLED##/ – wfaulk Oct 7 '09 at 16:47
Good call wfaulk. Even simpler. – Randall Oct 7 '09 at 16:53
You beat me to it by like 1 minute. – wfaulk Oct 7 '09 at 17:32
feedback
:%s/^\([^#]\)/##DISABLE##\1/
link|improve this answer
What is @? --padding-- – wfaulk Oct 7 '09 at 15:39
Sorry, that was meant to be a '%' – Paul Tomblin Oct 7 '09 at 15:45
feedback


sed -i -e 's/^\([^#]\)/#\1/g' /etc/cronfile

link|improve this answer
feedback
:%s/^\([#\n]\)\@!/##DISABLE##/g

the ^([#\n])\@! means "not # or newline at beginning of line"

Works for me in vim 7.2

link|improve this answer
Doesn't work in standard vi; no zero-width matches (\@!). – wfaulk Oct 7 '09 at 17:07
feedback

Maybe something like:

%s/^\([^#]\)\|!\($\)/##FOO##\1/g

I know its a mess with all those escapes, but the first part it the line does not start with # [^#], OR (The escaped pipe \| ) a line that is not empty ( ^$ )

link|improve this answer
You mean %s/^\([^#]\)\|!\($\)/##FOO##\1/g – mezgani Oct 7 '09 at 15:52
mezgani, right, thanks! – Kyle Brandt Oct 7 '09 at 15:58
Doesn't work in standard vi. Would work without the | or: :%s/^\([^#]\)/##FOO##\1/g – wfaulk Oct 7 '09 at 17:05
feedback
:map q /^[^#]<Enter>0i##DISABLE##<Esc>q
1Gq

This works in vim, but not in stock vi, which won't do tail recursion on mappings.

link|improve this answer
feedback

If you're using Vim, you may be interested in the EnhCommentify.vim plugin which lets you easily toggle comments.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown