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

How do I transform matched text to uppercase or lowercase directly inside a substitute replacement?

Answer

:s/pattern/\U&/g

Explanation

Vim's :substitute command supports case-transformation escape sequences in the replacement string. These modifiers let you uppercase, lowercase, or capitalize matched text without a separate command or external tool.

How it works

The following sequences can appear anywhere in the replacement string:

  • \u — convert the next character to uppercase
  • \U — convert all following characters to uppercase (until \E or end)
  • \l — convert the next character to lowercase
  • \L — convert all following characters to lowercase (until \E or end)
  • \E — end a \U or \L transformation
  • & or \0 — the entire matched text
  • \1, \2, ... — captured groups

Combine these with capture groups to reshape text without retyping it.

Example

Title-case all words in a file (capitalize first letter, lowercase the rest):

:%s/\v<(\w)(\w*)/\u\1\L\2/g

Input:

the QUICK brown FOX

Output:

The Quick Brown Fox

Or, to convert a snake_case identifier to UPPER_SNAKE_CASE:

:%s/\v\w+/\U&/g

Tips

  • \U& uppercases the whole match; \u& capitalizes only its first character
  • \L\1 lowercases an entire capture group — useful for normalizing inconsistent input
  • To end case conversion mid-replacement, insert \E: \U\1\E_suffix uppercases group 1 but leaves _suffix unchanged
  • Use \c in the search pattern for case-insensitive matching while still controlling the case of the replacement: :s/\cfoo/\UFoo/g
  • These modifiers also work in the expression register: :s/word/\=toupper(submatch(0))/g is equivalent to :s/word/\U&/g but with VimScript's toupper()

Next

How do I show both the absolute line number on the current line and relative numbers on all other lines?