How do I capitalize the first letter of every word in a file using a substitute command?
Answer
:%s/\w\+/\u&/g
Explanation
Vim's substitute command supports case-conversion modifiers in the replacement string. The \u modifier capitalizes the next character, and & represents the entire matched text. Combining them as \u& capitalizes just the first letter of each match, turning a file into title case in a single command.
How it works
%— apply to all lines in the files/— substitute command\w\+— match one or more word characters (a whole word)/\u&/g— replace with the match (&) with its first character uppercased (\u)
The key insight: & in the replacement refers to the entire match, and \u applies only to the first character of whatever follows it.
Example
Before:
the quick brown fox jumps over the lazy dog
After :%s/\w\+/\u&/g:
The Quick Brown Fox Jumps Over The Lazy Dog
Tips
- Use
\U&instead of\u&to uppercase the entire word, not just the first letter - For a selected range:
:'<,'>s/\w\+/\u&/g - To lowercase every word instead:
:%s/\w\+/\L&/g - The
\u,\l,\U,\Lmodifiers work in any:substitutereplacement — not just with& \Eor\eends a\Uor\Lcase region mid-replacement