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

How do I apply the last substitution's replacement to a different search pattern without retyping it?

Answer

:~

Explanation

The :~ command repeats the last substitution but uses the current search pattern instead of the original pattern. This lets you reuse the same replacement text across different searches — without retyping the replacement.

How it works

  • & — repeat last :s with the exact same search and replacement
  • :~ — repeat last :s with the last search (/) as the find pattern, keeping the same replacement

So if you last ran :s/FIXME/RESOLVED/ and then searched /TODO, running :~ executes :s/TODO/RESOLVED/.

Example

Start with a file containing two different markers:

FIXME: broken auth
TODO: refactor this

Run a substitution on the first marker:

:s/FIXME/DONE/

Now search for the second marker:

/TODO

Instead of retyping the replacement, repeat with the new pattern:

:~

Result: TODO: refactor this becomes DONE: refactor this.

Tips

  • Append g to replace all occurrences on the line: :~g
  • Use a range: :1,50~g to restrict to lines 1–50 with the current search
  • The companion & repeats the same :s exactly, and g& applies it file-wide
  • This is especially handy when doing a batch cleanup with the same replacement across many different patterns

Next

How do I extract regex capture groups from a string in Vimscript?