How do I reuse the replacement text from my last substitution in a new one without retyping it?
Answer
:s/pattern/~/
Explanation
In a Vim substitution, using ~ as the replacement string repeats the replacement text from the most recent :s command. This is handy when you want to apply the same transformation to a different pattern, or when you need to re-run a substitution with a different search term but the same result text.
How it works
~in the replacement field of:sexpands to the last used replacement string- It is distinct from
\~(which also works in some contexts) and from:~(a separate command that re-applies the last substitution with the last search pattern) - The remembered replacement persists until you run another
:scommand with a different replacement
Example
First, apply a substitution that replaces foo with [REDACTED]:
:%s/foo/[REDACTED]/g
Now, without retyping [REDACTED], apply the same replacement to a different pattern:
:s/secret_value/~/
This replaces secret_value with [REDACTED] — the ~ expanded to the previous replacement.
Before: api_key = secret_value
After: api_key = [REDACTED]
Tips
- Combine with
:~to apply the last substitute's search pattern as well: after:s/foo/bar/, running:%~repeats:s/foo/bar/across the whole file - Use
~when scripting repetitive transformations where the target varies but the replacement is always the same - See
:help s/~and:help :~to understand the subtle distinction between the two