How do I use yanked text as the replacement in a substitute command?
Answer
:%s/pattern/\=@0/g
Explanation
The \=@0 replacement expression inserts the contents of register 0 (last yank) as the replacement text. This lets you yank some text, then use it in a substitute command without retyping it.
How it works
- Yank the replacement text:
yiw(or any yank command) - Search and replace using the yanked text:
:%s/old_pattern/\=@0/g
Vim evaluates @0 as the contents of the yank register and uses it as the replacement.
Step-by-step example
" 1. Yank the word 'newFunction'
yiw
" 2. Replace all occurrences of 'oldFunction' with the yanked text
:%s/oldFunction/\=@0/g
Using other registers
" Use named register a
:%s/pattern/\=@a/g
" Use system clipboard
:%s/pattern/\=@+/g
" Use last search pattern as the search part (empty pattern)
:%s//\=@0/g
The ultimate yank-and-replace workflow
" 1. Yank replacement text
yiw
" 2. Search for the target (sets the search register)
*
" 3. Replace all with empty pattern (reuses *) and register 0
:%s//\=@0/g
Tips
\=@0is more reliable than trying to paste text with special characters into the replacement string- This handles newlines, slashes, and backslashes correctly — no escaping needed
@"is the unnamed register,@0is the yank register,@+is the clipboard- You can also use
<C-r>0in the command line to paste the register literally (but special chars may need escaping) - Documented under
:help sub-replace-expressionand:help expr-register