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
HopelessN00b
  • 53,385
  • 32
  • 133
  • 208

7 Answers7

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.

Randall
  • 606
  • 4
  • 4
1
:%s/^\([^#]\)/##DISABLE##\1/
Paul Tomblin
  • 5,217
  • 1
  • 27
  • 39
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.

wfaulk
  • 6,828
  • 7
  • 45
  • 75
0


sed -i -e 's/^\([^#]\)/#\1/g' /etc/cronfile
Ali Mezgani
  • 3,810
  • 2
  • 23
  • 36
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 ( ^$ )

Kyle Brandt
  • 82,107
  • 71
  • 302
  • 444
0
:%s/^\([#\n]\)\@!/##DISABLE##/g

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

Works for me in vim 7.2

0

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

Kamil Kisiel
  • 11,946
  • 7
  • 46
  • 68