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

How do I use Vim expressions and functions in substitute replacements?

Answer

:%s/\<\w\+\>/\=toupper(submatch(0))/g

Explanation

The \= flag in the replacement part of :substitute tells Vim to evaluate what follows as a Vimscript expression instead of treating it as a literal string. This unlocks the full power of Vim's function library in search-and-replace operations — you can call toupper(), tolower(), line(), printf(), or any other function.

How it works

  • :%s/ — substitute across the entire file
  • \<\w\+\> — matches each whole word
  • \= — signals that the replacement is a Vimscript expression
  • toupper(submatch(0)) — calls toupper() on the full match (submatch(0))
  • /g — apply to all matches on each line

Example

Before:

hello world foo bar

After :%s/\<\w\+\>/\=toupper(submatch(0))/g:

HELLO WORLD FOO BAR

Tips

  • Use submatch(1), submatch(2) etc. to access capture groups
  • Prepend line numbers: :%s/^/\=line('.').' '/ adds the current line number before each line
  • Increment all numbers: :%s/\d\+/\=submatch(0)+1/g
  • Format with printf: :%s/\d\+/\=printf('%03d', submatch(0))/g zero-pads numbers
  • Combine expressions: :%s/\(\w\+\)/\=len(submatch(1))>4 ? toupper(submatch(1)) : submatch(1)/g uppercases only words longer than 4 characters

Next

How do I return to normal mode from absolutely any mode in Vim?