sponsor Vim development Vim logo Vim Book Ad

intermediate Tip #298: Changing case with regular expressions

 tip karma   Rating 237/102, Viewed by 5413 

Read and edit this tip on the Vim tip wiki. The wiki may have a more recent version of this tip.

created:   August 5, 2002 10:41      complexity:   intermediate
author:   Jonathan McPherson      as of Vim:   5.7

I stumbled across this factoid on a website about vi. I haven't been able to locate it in the Vim documentation, but it works in Vim, and it's very handy.

There are times that you might like to go through a file and change the case of characters that match some arbitrary criteria. If you understand regular expressions well, you can actually do this fairly easily.

It's as simple as placing \U or \L in front of any backreferences in your regular expressions. Vim will make the text in the backreference uppercase or lowercase (respectively).

(A "backreference" is a part of a regular expression that refers to a previous part of a regular expression. The most common backrefernces are &, \1, \2, \3, ... , \9).

Some examples that demonstrate the power of this technique:

Lowercase the entire file -
:%s/.*/\L&/g

(& is a handy backreference that refers to the complete text of the match.)

Uppercase all words that are preceded by a < (i.e. opening HTML tag names):
:%s/<\(\w*\)/<\U\1/g

Please add a note if you know where this is in the documentation. I have done Ctrl-D searches on upper, lower, \U, and \L with no luck.

 rate this tip  Life Changing Helpful Unfulfilling 

<< Start in insert mode without loosing your escape key | Open file under cursor. >>

Additional Notes

[email protected], August 5, 2002 12:42
:help sub-replace-special

Got there quite simply by starting with :help :s.
pagaltzis () gmx _ net, August 8, 2002 12:58
Note also the gu<motion> and gU<motion> commands.

F.ex, ggguG will lowercase the entire file.
(gg = go to top, gu = lowercase, G = go to EOF).
[email protected], November 26, 2002 15:30
By using the \0 general backref instead of the name ones (\1, \2 etc) you can save some typing for on replace stanza of the regex.

This regex upper cases an explicit set of words to uppercase in a file.  
:%s/\(select\)\|\(order)\|\(by\)\|\(from\)\|\(where\)/\U\0/g

Not rocket science, but otherwise you'd have to do this:
:%s/\(select\)\|\(order)\|\(by\)\|\(from\)\|\(where\)/\U\1\U\2\U\3\U\4\U\5/g
[email protected], February 22, 2003 5:39
convert HTML-Tags to uppercase

:%s/<\/\=\(\w\+\)\>/\U&/g

or to lowercase

:%s/<\/\=\(\w\+\)\>/\L&/g
[email protected], February 21, 2005 14:14
Slightly off topic, but Shawn's regex to find words could be:
\(select\|order\|by\|from\|where\)
Actually, not that off-topic since he was talking about saving keystrokes :-)
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to the maillist. Help Bram help Uganda.
   
SourceForge.net Logo