13

I recently saw a substitute command where the author had the / replaced by a ! like this: :s!abc!ABC!g

I tried to find some documentation on this usage but I couldn't find anything relevant. So I tried to experiment by myself and once again I couldn't figure out the real difference between the two signs. Here's what I found:

  • It's not possible to mix ! and / in a command. For example :s!abc/ABC fails.
  • It may be useful to use ! to avoid escaping a /in a pattern. For example if I want to replace </ with % I can use :%s!</!%!g instead of :%s/<\//%/g.
  • It seems that in some case some regex won't work with / and works properly with ! but as I'm not really a regex expert i'm not sure of that.

So my question is simple: What is the advantage of using ! in a substitute command and when should I decide to use it instead of /?

22

From :help :global:

Instead of the '/' which surrounds the {pattern}, you can use any other single byte character, but not an alphabetic character, '\', '"' or '|'. This is useful if you want to include a '/' in the search pattern or replacement string.

As you already devised from your experimentation, this is to prevent the so-called "leaning toothpick syndrome". Consider this:

:%s/\/home\/martin\/test/\/home\/jake\/x/

versus:

:%s!/home/martin/test!/home/jake/x!

The second form is obviously a lot more readable.

This is the only reason you can change the delimiter; to make it more readable for us humans. The computer doesn't care.

Some other programs are even more flexible by the way, in GNU sed for example you can use x as delimiter if you wanted. sed sxaxbxg file is the same as sed s/a/b/g file.

  • As for readability, I prefer (and suggest) :%s@/home/martin/test@/home/jake/x@, as the "fat" @ makes it even easier to see where the individual parts of the statement begin / end. – DevSolar Dec 2 '15 at 15:32
  • @DevSolar I found :%s#/home/martin/test#/home/jake/x# works even better, but that's just personal opinion. – Amit Gold Aug 29 '16 at 14:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.