To comment out matches in Vim

Tag: vim Author: pc1436 Date: 2009-07-15

I would like to comment out each line which has the following match

^.*pdf

You need to somehow consider the situation by globbing. I try to make an object of the match by brackets.

I run unsuccessfully the following commands

%s/^(.*pdf)/^%$1/

and

%s/^(.*pdf)/^(%*$1)/

and

%s/^(.*pdf)/^%\$1/

How can you comment out the matches in Vim?

That * is not globbing, it is a Kleene closure and part of the regular expression pattern.

Best Answer

I'm not sure what you exactly mean by "comment out" (are comments indicated by hashes, or what?) but it looks like what you want is to prepend a % sign. In that case,

:g/pdf/s/^/%/

should work ("on all lines containing 'pdf', change the start of the line to a %" is how you could read it).

comments:

Thank you for your answer! - I did not know that you can combine the commands so nicely.
@Masi, the main power of Vim and related editors comes from the ability to combine the commands

Other Answer1

Hmm, I think you can get it working with:

:%s/^\(.*pdf\)/#\1/

or if you want to prepend '%' instead of '#':

:%s/^\(.*pdf\)/%\1/