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

How do I reuse my last search pattern literally in :substitute without re-escaping it?

Answer

:%s/\V<C-r>//gc

Explanation

When your last search pattern contains punctuation, slashes, or regex atoms, retyping it inside :substitute is error-prone. This pattern reuses the previous search directly from the search register and forces a literal match, so you can focus on the replacement itself. It is especially useful in large files where interactive confirmation matters.

How it works

:%s/\V<C-r>//gc
  • :%s/ starts a substitution across the whole buffer
  • \V switches the pattern to very nomagic (treats most characters literally)
  • <C-r>/ inserts the contents of the search register (@/) into the command-line
  • The second / starts the replacement field
  • g replaces all matches per line
  • c asks for confirmation at each match

This is much safer than manually escaping a complex prior search. You can keep iterating by searching first (/pattern) and then promoting that exact pattern into a replacement pass.

Example

Suppose you searched for:

foo/bar.baz

Now you want to replace every literal occurrence with qux and confirm each change. Run:

:%s/\V<C-r>//qux/gc

Vim inserts the exact last search and prompts you through each replacement.

Tips

  • Remove c when you are ready to apply changes non-interactively
  • Use a range like :'<,'> instead of % to limit replacement to a visual selection

Next

How do I launch a GDB session in Vim with the built-in termdebug plugin?