0

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

7 Answers 7

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

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


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

0
:%s/^\([#\n]\)\@!/##DISABLE##/g

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

Works for me in vim 7.2

1
  • Doesn't work in standard vi; no zero-width matches (\@!).
    – wfaulk
    Oct 7, 2009 at 17:07
0

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

2
  • You mean %s/^\([^#]\)\|!\($\)/##FOO##\1/g Oct 7, 2009 at 15:52
  • Doesn't work in standard vi. Would work without the | or: :%s/^\([^#]\)/##FOO##\1/g
    – wfaulk
    Oct 7, 2009 at 17:05
0
: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.

0

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

You must log in to answer this question.