How do I transform matched text to uppercase or lowercase directly inside a substitute replacement?
Answer
:s/pattern/\U&/g
Explanation
Vim's :substitute command supports case-transformation escape sequences in the replacement string. These modifiers let you uppercase, lowercase, or capitalize matched text without a separate command or external tool.
How it works
The following sequences can appear anywhere in the replacement string:
\u— convert the next character to uppercase\U— convert all following characters to uppercase (until\Eor end)\l— convert the next character to lowercase\L— convert all following characters to lowercase (until\Eor end)\E— end a\Uor\Ltransformation&or\0— the entire matched text\1,\2, ... — captured groups
Combine these with capture groups to reshape text without retyping it.
Example
Title-case all words in a file (capitalize first letter, lowercase the rest):
:%s/\v<(\w)(\w*)/\u\1\L\2/g
Input:
the QUICK brown FOX
Output:
The Quick Brown Fox
Or, to convert a snake_case identifier to UPPER_SNAKE_CASE:
:%s/\v\w+/\U&/g
Tips
\U&uppercases the whole match;\u&capitalizes only its first character\L\1lowercases an entire capture group — useful for normalizing inconsistent input- To end case conversion mid-replacement, insert
\E:\U\1\E_suffixuppercases group 1 but leaves_suffixunchanged - Use
\cin the search pattern for case-insensitive matching while still controlling the case of the replacement::s/\cfoo/\UFoo/g - These modifiers also work in the expression register:
:s/word/\=toupper(submatch(0))/gis equivalent to:s/word/\U&/gbut with VimScript'stoupper()