vimtricks.wiki Concise Vim tricks, one at a time.

How do I change the case of text during a search and replace?

Answer

:%s/\<word\>/\u&/g

Explanation

Vim's substitute command supports case conversion modifiers in the replacement string. These let you uppercase, lowercase, or title-case matched text as part of the replacement.

Case modifiers

Modifier Effect
\u Uppercase the next character
\U Uppercase everything that follows
\l Lowercase the next character
\L Lowercase everything that follows
\e or \E End case conversion

Examples

" Capitalize first letter of matched word
:%s/\<error\>/\u&/g
" error → Error

" Uppercase entire match
:%s/\<error\>/\U&/g
" error → ERROR

" Lowercase entire match
:%s/\<ERROR\>/\L&/g
" ERROR → error

" Title case using capture groups
:%s/\(\w\)\(\w*\)/\u\1\L\2/g
" hello world → Hello World

" Convert snake_case to camelCase
:%s/_\(\l\)/\u\1/g
" my_variable_name → myVariableName

Tips

  • & in the replacement refers to the entire match
  • \1, \2 refer to capture groups
  • Combine \U and \e to uppercase only part of the replacement: \U\1\e_\2
  • This is especially useful when renaming variables, converting naming conventions, or normalizing text

Next

How do I always access my last yanked text regardless of deletes?