How do I use a register value as the replacement string in a substitution?
Answer
:%s/pattern/\=@a/g
Explanation
How it works
In Vim's substitute command, the replacement string can be a Vimscript expression when prefixed with \=. The expression @a evaluates to the contents of register a. Combined, :%s/pattern/\=@a/g replaces every occurrence of pattern with whatever text is stored in register a.
This technique is powerful because:
- The replacement text can contain characters that would normally need escaping in a substitution (like
/,&,~,\) - You can yank complex text once and use it as a replacement without worrying about special characters
- You can combine it with other expressions for dynamic replacements
The \= prefix tells Vim to evaluate what follows as a Vimscript expression. You can use any expression, not just registers:
\=@a-- contents of registera\=@0-- contents of the yank register\=@+-- contents of the system clipboard\=line('.')-- current line number\=submatch(0)-- the matched text itself (useful for wrapping)
Example
Suppose you want to replace all occurrences of PLACEHOLDER with a multi-line address block:
-
Yank the address block into register
a:- Navigate to the address text
- Visual-select it and type
"ay
-
Run the substitution:
:%s/PLACEHOLDER/\=@a/g
This inserts the entire address block (including newlines) wherever PLACEHOLDER appeared. Without the \= expression approach, inserting multi-line text in a substitution would require \r for each newline.
Another example: replace every TODO with the current filename:
:%s/TODO/\=@%/g
The @% register always holds the current filename.