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

How do I add line numbers to the beginning of every line using a substitute expression?

Answer

:%s/^/\=line('.').' '/

Explanation

Vim's substitute command supports expressions in the replacement string using \=. This lets you call Vim functions dynamically for each match, enabling powerful transformations like adding line numbers, performing arithmetic, or generating sequential values.

How it works

  • :%s — substitute across all lines in the file
  • /^/ — match the beginning of each line
  • /\=line('.').' '/ — the \= flag tells Vim the replacement is an expression. line('.') returns the current line number, and .' ' concatenates a space after it

Example

Before:

apple
banana
cherry
date

After running :%s/^/\=line('.').' '/:

1 apple
2 banana
3 cherry
4 date

Tips

  • Use printf() for formatted numbers: :%s/^/\=printf('%03d ', line('.'))/ produces zero-padded numbers like 001, 002
  • For numbering starting from a specific value, use arithmetic: :%s/^/\=(line('.')+99).' '/
  • Combine with a range to number only specific lines: :5,10s/^/\=line('.').' '/
  • The expression replacement also works with submatch() to transform captured groups: :%s/\(\d\+\)/\=submatch(0)*2/g doubles all numbers in the file

Next

How do I ignore whitespace changes when using Vim's diff mode?