How do I change the case of matched text in a substitute replacement using \u, \U, \l, or \L modifiers?
Answer
:s/\(\w\+\)/\u\1/g
Explanation
Vim's substitute command supports case-change modifiers in the replacement string that let you capitalize, uppercase, or lowercase matched text as part of the substitution — no separate pass needed. These modifiers apply to whatever immediately follows them: literal text, & (whole match), or back-references like \1.
How it works
| Modifier | Effect |
|---|---|
\u |
Uppercase the next character only |
\l |
Lowercase the next character only |
\U |
Uppercase everything until \E or end of replacement |
\L |
Lowercase everything until \E or end of replacement |
\E |
End a \U or \L block |
The command :s/\(\w\+\)/\u\1/g uses \u to capitalize the first letter of each captured word group (\1) on the current line.
Example
:s/\(\w\+\)/\u\1/g
Given:
hello world vim
Result:
Hello World Vim
Tips
- Uppercase an entire capture group:
:s/const \(\w\+\)/const \U\1\E/ - True title case (capitalize first, lowercase rest):
\u\L\1 - Apply to whole match with
&::%s/error/\U&/guppercases everyerror - Combine with
\v(very magic) for cleaner patterns::%s/\v(\w+)/\u\1/g - These modifiers are Vim-specific — not available in all regex dialects