Reputation: 76
Vim substitute command :%s/old/new/g
will replace all occurrences of old
by new
. But I want to do this replacement only in lines that do not start with #
. I mean in my file there are some lines starting with # (called commented lines) which I want to exclude in search replace. Is there any way to do it?
Upvotes: 2
Views: 918
Reputation: 6026
The Answer from Thomas is fine. Another approach would be the negative lookbehind:
:%s/\(#.*\)\@<!old/new/g
These method matches every old
not preceded by a #
while the method of Thomas matches every line not starting with #
and then matches every old
on that line.
The solution of Kent is a little bit more elegant. It uses :v
which is the same as :g!
. It matches every line starting with #
and then runs the command on every other line. This has the advantage that the regex gets easier. In your usecase the regex to not match it is quite easy, but often it is way easier to build a regex to match a criteria than one that doesn't match. so the :v
command helps here.
In your case the global
(both of the other answers are using global
) command seems safer, since it only checks for a #
at the beginning of the line. But depending on the usecase all of the three methods have their advantages
Upvotes: 3
Reputation: 7517
You should mix it with the g
(see help :global
) command:
:%g/^[^#]/s/old/new/
Upvotes: 11