eveo
eveo

Reputation: 2833

How do you comment out all non-blank non-commented lines in a file?

I have a file that I want to add a # in front of, avoiding any blank lines. The config in question can be found at: https://github.com/koekeishiya/skhd/blob/master/examples/skhdrc

I want to comment them all out and then go through and uncomment what I need.

Upvotes: 0

Views: 176

Answers (3)

SergioAraujo
SergioAraujo

Reputation: 11800

The bellow search matches only non-blank lines that do not start with #. (Thanks @Ry) for his commenting it helped me to give a conciser answer.

/^#\@!.

# .................. literal #
\@! ................ negates preceding  atom
.   ................  any char

So the solution becomes:

:%s/#@!./# &

& ............... the whole search pattern

Tip: once you make a search you can do this:

:%s//# &

The double slashes mean: use the last search on my substitution.

Upvotes: 0

Ry-
Ry-

Reputation: 224904

Substitution requiring a leading non-# achieves both at once:

:%s/^[^#]/#&

Upvotes: 3

D. Ben Knoble
D. Ben Knoble

Reputation: 4673

An alternate solution:

:global/^[^#]/s/^/#

And if you don't mind the possibility of duplicate #s, use . as the global pattern instead:

:global/./s/^/#

I'd even argue that this is the best, since then you can find commented out code with by searching for ^#[^#], and original comments by searching for ^##.

In either form, instead of substitute-ing, you can "insert" by changing the command following global to :normal! I#


:global can be shortened to :g, and :normal! to :norm! (in most cases).

Upvotes: 0

Related Questions