Reputation: 24593
I have some text which has some %
and some \%
. I want to replace all occurrences of %
with \%
, without converting \% to \\%
. I tried:
%s/\\\@!%/\\%/g
But it is not working.
Sample text can be:
This % and this % should be replaced but not these two: \% and \%.
Thanks for your help.
Upvotes: 1
Views: 129
Reputation: 23677
We can make use of greediness of ?
here
:%s/\\\?%/\\%/g
\\\?
will match \
zero or one time. As ?
is greedy, it will consume if \
is present\%
and %
will get replaced with \%
Upvotes: 3
Reputation: 25
From the console
echo Replace % and % but not \% and \%. |sed -e s/%/\\\%/g
Gives Replace % and % but not \% and \%.
Hope that's what you're looking for. If so, just do the whole file with
cat FileName |sed -e s/%/\\\%/g
Upvotes: -1
Reputation: 338316
Vim supports negative look-behinds, like this:
:s/\(\\\)\@<!%/\\%/g
This breaks down as:
s/ # substitute...
\( # start group 1
\\ # a backslash
\) # end group 1
\@<! # group option: negative look-behind
% # a "%" sign
/ # with...
\\% # "\%"
/g # globally.
You could also do :s/%/\\%/g
followed by :s/\\\\%/\\%/g
.
Upvotes: 2