Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
share|improve this question
: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
:%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


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

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

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
: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

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

share|improve this answer

Your Answer

 
discard

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