8

I recently found a substitute command for vim where the author had the / replaced by a ! like this: :%s!foo!bar and I don't understand the difference with the traditionnal :%s/foo/bar.

I searched some documentation on this syntax but I didn't find anything relevant, so I tried to experiment by myself and I couldn't figure out clearly the difference between the two forms. Here is what I found:

  • You can't mix / and ! in the same command. E.g: :%s/foo!bar will fail.
  • The sign ! can be useful with patterns including a /. For example if I want to replace </ with % in my file I can do :%s!</!%!g instead of :%s/<\//%/g: I don't need to escape / in the first command, but I'd be surprised if that was the only use of !.
  • Some regex seems to fail with / and work propertly with ! but as I'm far from being a regex master I'm not sure about this point.

So my question is: what is the difference between / and ! in vim substitution and when should I use one instead of the other?

statox
  • 2,827
  • 1
  • 21
  • 41

1 Answers1

12

Both can be used as long they are consistent (not mixed). Usually / is used. But other char can be used if the string you want to replace contains multiple /. For example :

:%s!/usr/local/bin!/usr/bin!
:%s:/usr/local/bin:/usr/bin:
:%s,/usr/local/bin,/usr/bin,
tivn
  • 1,883
  • 14
  • 14
  • Ok thank you for your answer! Where can I found a list of the char which can be used as separator? Or the ones which can not be used? – statox May 03 '15 at 16:25
  • 1
    @statox, it is documented in `:help E146` ( from `:help change.txt` ) . – tivn May 03 '15 at 16:28