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

How do I use expressions in Vim's substitute replacement?

Answer

:%s/pattern/\=expression/g

Explanation

Vim's substitute command supports expression replacements using \= in the replacement string. Instead of a literal replacement, Vim evaluates a Vimscript expression for each match, letting you perform calculations, call functions, or build dynamic replacements.

How it works

  • :%s/pattern/\=expression/g replaces each match with the result of evaluating expression
  • Inside the expression, submatch(0) returns the entire match, submatch(1) returns the first capture group, and so on
  • Any valid Vimscript expression can be used: arithmetic, string functions, even system() calls

Example

Increment every number in a file by 1:

:%s/\d\+/\=submatch(0)+1/g

Given the text:

item 1 costs 50
item 2 costs 100

The result is:

item 2 costs 51
item 3 costs 101

Another example — wrap every match in parentheses:

:%s/\w\+/\='(' . submatch(0) . ')'/g

Tips

  • Use submatch(0)+1 for incrementing, submatch(0)*2 for doubling
  • Combine with printf() for formatted output: \=printf('%03d', submatch(0)+1)
  • Use line('.') inside the expression to get the current line number during substitution
  • Use toupper(submatch(0)) or tolower(submatch(0)) for case transformations
  • This is one of the most powerful features in Vim that most users never discover

Next

How do I edit multiple lines at once using multiple cursors in Vim?