How do I change the case of matched text in a Vim substitute command?
Answer
\u and \l in :s replacement
Explanation
Vim's substitute command supports special case modifiers in the replacement string that let you change the case of captured text on the fly. This is powerful for reformatting identifiers, fixing capitalization, or transforming data without multiple steps.
How it works
\u— uppercase the next character\U— uppercase all following characters (until\eor\E)\l— lowercase the next character\L— lowercase all following characters (until\eor\E)\eor\E— end case modification
These go in the replacement part of :s and apply to whatever follows them, including backreferences like \1.
Example
Capitalize the first letter of every word on a line:
Before: hello world foo bar
After: Hello World Foo Bar
:s/\<\(\w\)/\u\1/g
Convert an entire match to uppercase:
Before: status: ok
After: status: OK
:s/ok/\U&/
Tips
- Combine
\Uand\eto uppercase only part of the replacement:\U\1\e_\2 - Use
&in the replacement to refer to the entire match - Works with
:%sfor file-wide transformations