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

How do I reuse my last search pattern in a substitute command without retyping it?

Answer

:%s//new/g

Explanation

Leaving the search field empty in a :s command tells Vim to reuse the last search pattern from / or *. This means you can craft and test a complex search incrementally, then run a substitution without retyping or pasting the pattern.

How it works

  • /complicated\(regex\)pattern<CR> sets the last search pattern and highlights matches
  • :%s//replacement/g uses that same pattern — the empty // tells Vim "use whatever I last searched for"
  • This works because Vim stores the last search pattern in the / register, and an empty search field in :s defaults to that register

Example

Suppose you need to replace a tricky pattern. First, build and verify it with search:

/\<\d\{4\}-\d\{2\}-\d\{2\}\>

Vim highlights all date-like strings (2024-01-15, 2023-12-31, etc.) so you can confirm the pattern is correct. Now substitute without retyping:

:%s//DATE_REDACTED/g

Given the text:

Created: 2024-01-15
Modified: 2023-12-31
Expires: 2025-06-01

The result is:

Created: DATE_REDACTED
Modified: DATE_REDACTED
Expires: DATE_REDACTED

Tips

  • Use * on a word to set the search pattern to that word (with boundaries), then :%s//replacement/g to replace it everywhere
  • The c flag still works: :%s//replacement/gc lets you confirm each match interactively
  • You can also reuse the pattern in the replacement side with & or \0: :%s//(&)/g wraps every match in parentheses
  • Press <C-r>/ in the command line to paste the last search pattern if you want to see or modify it before substituting
  • This technique pairs perfectly with incremental search (:set incsearch) for building patterns visually before committing to a replacement
  • The same empty-pattern trick works with :g and :v: :g//d deletes all lines matching your last search

Next

How do I edit multiple lines at once using multiple cursors in Vim?