How do I insert line numbers or computed values into substitute replacements?
Answer
:%s/pattern/=line('.')/g
Explanation
Using \= at the start of the replacement string in a :s command tells Vim to evaluate the rest as a Vimscript expression instead of literal text. This unlocks computed replacements — inserting line numbers, performing arithmetic, calling functions, and even referencing external state.
How it works
:%s/pattern/\=expression/g— for each match, evaluateexpressionand use its result as the replacementline('.')— returns the current line numbersubmatch(0)— returns the matched text (like&in normal replacements)submatch(1)— returns the first capture group
Examples
Add line numbers before each line:
:%s/^/\=line('.') . '. '/
Before: apple → After: 1. apple
Double all numbers in the file:
:%s/\d\+/\=submatch(0) * 2/g
Replace with a calculated value using a function:
:%s/\<TODO\>/\='DONE-' . strftime('%Y%m%d')/g
Produces: DONE-20260219
Number items in a list sequentially (using a counter):
:let n=0 | %s/- /\='- ' . (n+=1) . '. '/g
Tips
submatch(0)inside\=is the equivalent of&or\0in a normal replacement- You can call any Vimscript function:
printf(),tolower(),toupper(),strftime(), etc. - Chain expressions with
.(string concatenation):\=submatch(1) . '-' . submatch(2) - This is one of Vim's most powerful substitution features — it effectively turns
:sinto a map/transform operation