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

How do I uppercase or lowercase matched text directly in a substitute command?

Answer

:%s/pattern/\U&/g

Explanation

Vim's substitute replacement string supports special case-transform atoms that change the case of matched text without requiring a second pass or an external tool. Use \U, \L, \u, \l, and \E in the replacement side of :s to uppercase, lowercase, capitalize, or end a case transformation.

How it works

Atom Effect
\U Uppercase everything that follows until \E or end of replacement
\L Lowercase everything that follows until \E or end of replacement
\u Uppercase only the next character
\l Lowercase only the next character
\E End the effect of \U or \L
& The entire matched text (same as \0)

These atoms apply to whatever text follows them in the replacement string, including back-references like \1, \2, or &.

Example

Convert all http occurrences to uppercase:

:%s/http/\U&/g

Before:

The http protocol is older than https.

After:

The HTTP protocol is older than HTTPS.

Capitalize the first letter of every word matched by a pattern:

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

Transform snake_case to CamelCase by capitalizing after each underscore:

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

Tips

  • Combine \u with capture groups to selectively capitalize: :%s/\(\w\+\)/\u\1/g capitalizes the first letter of every word
  • \L is handy for normalizing inconsistently-cased identifiers before a bulk rename
  • These atoms work in any substitute context: :s, :%s, :'<,'>s, :g/pat/s///

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?