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

How do I use case conversion metacharacters in Vim substitution replacement strings?

Answer

\U, \L, \u, \l, \e in :substitute replacement

Explanation

Vim's substitute command supports in-replacement case conversion metacharacters that transform the case of matched text without extra scripting. Six metacharacters control single-character and span-based case changes, with \e and \E acting as explicit terminators.

How it works

Metachar Effect
\u Make the next character uppercase
\l Make the next character lowercase
\U Uppercase all following chars until \e/\E or end of replacement
\L Lowercase all following chars until \e/\E or end of replacement
\e / \E End the effect of \U or \L

Example

Capitalize the first letter of every word:

:%s/\v\w+/\u&/g
Before:  the quick brown fox
After:   The Quick Brown Fox

Uppercase only the first 3 characters of each identifier, keeping the rest unchanged:

:%s/\v(\w{3})(\w+)/\U\1\e\2/g
Before:  fooBar bazQux
After:   FOOBar BAZQux

Without \e, \U\1\2 would uppercase the entire match (both capture groups). The \e after \1 terminates \U so \2 remains unchanged.

Tips

  • \e and \E are interchangeable terminators — use whichever is less confusing in context
  • Combine with \= (expression register): :%s/\v\w+/\=toupper(submatch(0))/g is equivalent to \U& for whole-word uppercasing
  • Works in all :substitute variants including :g/pattern/s//replacement/g chained commands
  • Switch to \v (very magic) to reduce backslash noise in patterns

Next

What is the difference between the inner word (iw) and inner WORD (iW) text objects in Vim?