18

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 /?

0

1 Answer 1

27

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.

Also see :help pattern-delimiter.

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. I prefer to use ! or | for this as it's the most similar to /, but other prefer @, #, ^, or something else.

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, although I don't think that's especially readable.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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