Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

share|improve this question
add comment

7 Answers

:%s/^\([^#]\)/##DISABLE##\1/
share|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
add comment
: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.

share|improve this answer
add comment


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

share|improve this answer
add comment

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 ( ^$ )

share|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
add comment
:%s/^\([#\n]\)\@!/##DISABLE##/g

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

Works for me in vim 7.2

share|improve this answer
    
Doesn't work in standard vi; no zero-width matches (\@!). –  wfaulk Oct 7 '09 at 17:07
add comment
: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.

share|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
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

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