Change case during substitution
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\+@\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: