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

How do I change the case of captured text in a :substitute replacement?

Answer

\u / \l / \U / \L (in :s replacement)

Explanation

Vim's :substitute replacement string supports case-conversion modifiers that let you uppercase or lowercase matched text without writing a separate command. These are especially powerful when combined with capture groups.

How it works

  • \u — uppercase the next character in the replacement
  • \l — lowercase the next character in the replacement
  • \U — uppercase all following characters until \E or end of replacement
  • \L — lowercase all following characters until \E or end of replacement
  • \E — end the \U or \L block

Examples

Capitalize the first letter of every word (title case):

Input:  hello world foo bar
:%s/\<\w/\u&/g
Output: Hello World Foo Bar

Convert snake_case to CamelCase:

Input:  my_variable_name
:%s/_\(\w\)/\u\1/g
Output: myVariableName

Lowercase all matched words:

:%s/ERROR/\L&/g

Converts ERRORerror, FATAL ERRORfatal error, etc.

Tips

  • & refers to the entire match; \1, \2 refer to capture groups
  • Combine \U with \E to uppercase only part of the replacement: \U\1\E-\2
  • These modifiers work in all :s variants including :%s, :'<,'>s, and :cdo s/...

Next

How do I stop Vim from automatically continuing comment markers when I press Enter or open a new line?