How do I use a Vimscript expression as the replacement in a substitute command?
Answer
:%s/pattern/\=expr/g
Explanation
Prefixing the replacement field of :s with \= tells Vim to evaluate the rest as a Vimscript expression and use its result as the replacement string. This unlocks transformations that are impossible with static replacement text.
How it works
\=signals that the replacement is an expression, not a literal string- Inside the expression,
submatch(0)returns the full match;submatch(1)returns the first capture group, and so on - Any Vimscript function can be called:
toupper(),tolower(),printf(),len(), arithmetic operators, etc.
Example
Double every integer in a file:
:%s/\d\+/\=submatch(0)*2/g
Before:
retry 3 times with 10 second timeout
After:
retry 6 times with 20 second timeout
Pad numbers to 4 digits with leading zeros:
:%s/\d\+/\=printf('%04d', submatch(0))/g
Tips
- Combine with
\(\)capture groups andsubmatch(n)to perform conditional or context-aware replacements - Use
\=system('cmd')to call external tools and insert their output as the replacement - Chain multiple transformations:
\=toupper(submatch(1)) . submatch(2)to uppercase only the first capture group