UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 30.16 Counting Occurrences; Stopping Search Wraps Chapter 30
vi Tips and Tricks
Next: 30.18 Setting vi Options Automatically for Individual Files
 

30.17 Capitalizing Every Word on a Line

Are you typing the title of an article or something else that needs an uppercase letter at the start of every word? Do you need to capitalize some text that isn't? It can be tedious to press the SHIFT key as you enter the text, or to use ~ (tilde) and w commands to change the text. The command below capitalizes the first character of every word.

\< \u 
:s/\<./\u&/g

(You might be wondering why we didn't use :s/\<[a-z]/\u&/g to match lowercase letters. The <. actually matches the first character of every word, but the \u will only affect letters. So, unless you only want to capitalize certain letters, <. is enough.)

The example above does only the current line. You can add a range of lines after the colon. For example, to edit all lines in the file:

% 
:%s/\<./\u&/g

To do the current line and the next five, use:

.,+5 
:.,+5s/\<./\u&/g

To make the first character of each word uppercase (with \u) and the rest lowercase (with \L), try:

\(...\)...\1 
:s/\<\(.\)\([A-Za-z]*\)\>/\u\1\L\2/g

The command above doesn't convert the back ends of words with hyphens (like CD-ROM) or apostrophes (like O'Reilly) to lowercase. That's because the [A-Za-z]*\> only matches words whose second through last characters are all letters. You can add a hyphen or an apostrophe to make that expression match more words, if you'd like.

Those commands can be a pain to type. If you use one of them a lot, try putting it in a keymap (31.2).

- JP


Previous: 30.16 Counting Occurrences; Stopping Search Wraps UNIX Power ToolsNext: 30.18 Setting vi Options Automatically for Individual Files
30.16 Counting Occurrences; Stopping Search Wraps Book Index30.18 Setting vi Options Automatically for Individual Files

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System