Change case during substitution

4.3
(58)

We recently covered how to insert the matched pattern into your substitution replacement. In addition to simply using the matched pattern as-is, Vim allows you to manipulate the case of the original pattern when substituting it.

  • \U – when used in a replacement pattern, uppercases everything after it
  • \L – lowercases everything after it
  • \u – uppercases the first character of what follows
  • \l – lowercases the first character of what follows
  • \e or \E – stops the uppercasing or lowercasing

How would we use these? Well, we can combine them with the previous tip of using & in the substitution pattern. Or we can use numbered captures such as \1, \2, etc. for more advanced matching. Either way, we prepend one of these escaped characters before the portion we wish to manipulate. For example, we could find all the email addresses and lower case them:

:%s/\S\[email protected]\S\+/\L&/

The key portion there is the \L before the &. This means we will lowercase everything afterwards.

Here’s another one. Let’s say we want to lowercase the name portion of the email address but leave the company casing intact. So [email protected] would become [email protected]. In this case, we’ll need to use \e (or also \E will work) to end the manipulation of our character case halfway through our substitution pattern. The final replacement would look like so:

:%s/\(\S\+\)\(@\S\+\)/\L\1\e\2/g

The important bit here is the substitution again. We use \L to begin lowercasing, then \1 for the first capture (such as FirstLast), then \e to end the lowercasing followed by \2 for the second capture (such as @Company.com). The result is that the first portion of the email is lowercased and everything else is kept the same.

Here I’ve demonstrated the first of these:

How useful was this post?

Average rating 4.3 / 5. Vote count: 58

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

61 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts

2 thoughts on “Change case during substitution”

Leave a reply

Your email address will not be published. Required fields are marked *