vimtricks.wiki Concise Vim tricks, one at a time.

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, evaluate expression and use its result as the replacement
  • line('.') — returns the current line number
  • submatch(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 \0 in 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 :s into a map/transform operation

Next

How do I run a search and replace only within a visually selected region?