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

How do I use a Vim expression to dynamically compute the replacement string in a substitution?

Answer

\=

Explanation

In a substitute command, using \= at the start of the replacement string tells Vim to evaluate the rest as a Vim expression rather than a literal string. The expression's return value becomes the replacement text. This unlocks dynamic transformations that a static replacement string cannot do.

How it works

  • :%s/pattern/\=expression/g — replace each match with the evaluated expression
  • Inside the expression, submatch(0) holds the entire match, submatch(1) holds group 1, etc.
  • Any Vim function or expression can be used: arithmetic, toupper(), system(), printf(), etc.

Example

Increment all version numbers in a file:

version = 3
api_version = 12

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

version = 4
api_version = 13

Convert all-caps identifiers to title case:

FOO_BAR baz QUX

Run: :%s/[A-Z_]\+/\=substitute(tolower(submatch(0)), '_', ' ', 'g')/g

Tips

  • Chain functions: \=printf('%05d', submatch(0)+1) for zero-padded numbers
  • Use \=system('date -u') to insert current timestamp (strips trailing newline with trim())
  • Works with capture groups: :%s/\(\w\+\)/\=toupper(submatch(1))/ uppercases the first word
  • The full power of Vim's expression language is available — variables, conditionals, and user functions

Next

How do I rename a variable across all case variants (snake_case, camelCase, MixedCase) at once?