rnso
rnso

Reputation: 24593

Replace % with \% if not already replaced in vim

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

Answers (3)

Sundeep
Sundeep

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
  • So, in effect, both \% and % will get replaced with \%

Upvotes: 3

Mel
Mel

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

Tomalak
Tomalak

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

Related Questions