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

How do I use case-transformation atoms in substitute replacements to capitalize or lowercase matched text?

Answer

:%s/\w\+/\u&/g

Explanation

Vim's substitute command supports special case-transformation atoms in the replacement string that let you change the case of matched text without a plugin. The atoms \u, \U, \l, and \L give you fine-grained control over how replacements are cased.

How it works

These atoms apply to the replacement portion (right-hand side) of a :s command:

  • \u — uppercase the next character of the replacement
  • \U — uppercase all subsequent characters until \E or end of replacement
  • \l — lowercase the next character of the replacement
  • \L — lowercase all subsequent characters until \E or end of replacement
  • \E (or \e) — end a \U or \L sequence
  • & — refers to the entire matched text (the whole match)
  • \1, \2 — refer to capture groups

Example

Given the text:

hello world

Running :%s/\w\+/\u&/g capitalizes the first letter of each word:

Hello World

To convert a snake_case identifier to TitleCase, you can combine groups and case atoms:

:%s/\v_(\w)/\u\1/g

This removes the underscore and uppercases the letter that follows it.

To uppercase an entire match:

:%s/FIXME/\U&/g

To lowercase everything except the first character:

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

Tips

  • These atoms only work in the replacement side of :s, not in search patterns
  • Combine \U...\E and \L...\E for mixed-case transformations in a single substitution
  • Works great with \v (very magic) for cleaner capture group syntax

Next

How do I hard-wrap the current paragraph to the textwidth in Vim?