Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim what is the use of exclamation mark in substitute command

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?

like image 699
statox Avatar asked May 03 '15 16:05

statox


1 Answers

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,
like image 119
tivn Avatar answered Sep 27 '22 18:09

tivn