vimtricks.wiki Concise Vim tricks, one at a time.

How do I avoid backslash-escaping slashes in a substitution when replacing file paths or URLs?

Answer

:s#pattern#replacement#g

Explanation

Vim's substitution command accepts any non-alphanumeric, non-whitespace character as the delimiter — not just /. Swapping the delimiter removes the need to escape every / in file paths, URLs, or regex anchors, making the command far more readable.

How it works

The syntax :s/{pat}/{rep}/[flags] works because / is the conventional delimiter — it is not hardcoded. You can use #, |, @, !, ,, or any other non-special character as long as it is consistent across the command:

:s#/old/path#/new/path#g

This replaces without requiring a single backslash, compared to the escaped form:

:s/\/old\/path/\/new\/path/g

The same flexibility applies to :g, :v, and pattern-based range expressions:

:g#https://old.example.com#d

Example

Given a file containing:

include /usr/local/lib/config.h

Running :s#/usr/local/lib#/opt/homebrew/lib#g produces:

include /opt/homebrew/lib/config.h

Tips

  • The delimiter must be used consistently throughout: :s@old@new@ not :s@old/new@
  • Works with ranges: :'<,'>s|http://|https://|g to upgrade HTTP links in a selection
  • The :g command also supports alternative delimiters: :g!/^#/d deletes lines not starting with #

Next

How do I enable matchit so % jumps between if/else/end style pairs?