I often use # key to quickly search for a keyword. I want to change the case of the last searched pattern in the easiest possible way.

One way to do this is to use \U\1 in the substitution part and pressing Ctrl-r followed by / in the search part of the standard substitution command, like this:

:%s/\(<Ctrl-r>/\)/\U\1/g

However, this is too unwieldy.

Is there some fast way to do this? That is, I press # key and then 4-5 keystrokes later, I have changed the case of all the matches.

  • :%s//\U\1/g an empty pattern uses the last search pattern. I am pretty sure we have a duplicate question on here, but I can't find it. – statox Jul 13 at 14:00
  • @statox No. :%s//\U\1/g doesn't work. It simply deletes all the values matching the last searched pattern. – shivams Jul 13 at 14:01
  • 2
    Instead of \1, use & (or \0, which is the same) – Luc Hermitte Jul 13 at 14:30
  • @LucHermitte : You nailed it!! This is certainly fast. Please post this as answer. – shivams Jul 13 at 14:34
  • Well, statox had the solution, but he missed the unneeded group :) – Luc Hermitte Jul 13 at 14:37
up vote 2 down vote accepted

There are two little things to change

  1. First :s (and well as other search commands) will search the last searched pattern if we double the separator (usually /).
  2. Then of course, there is no longer a group. So we cannot use \1. Fortunately, there is the match everything group: \0, or its shortcut: &

Hence:

:s//\U&/g

You can use gUgn to upper-case the next search match. Then press . repeatedly to keep changing more matches.

Note: This will not work with 'ignorecase' enabled (because the ignorecase setting will make gn select the current match over and over again). You can toggle the setting with :set ic! if needed (or add the \C atom to your pattern, which will make sure that the 'ignorecase' option does not apply).

  • Wow. That is one creative solution. However, . doesn't work here. Can you clarify? – shivams Jul 13 at 16:43
  • Works for me, maybe your vim is too old? – Mass Jul 13 at 18:20
  • 1
    Or g~ to actually invert the case – D. Ben Knoble Jul 13 at 21:51
  • 1
    @shivams I don't suppose you have 'ignorecase' enabled? I inadvertently tried it without doing :set noic first and things appeared to be broken when I hit .. – B Layer Aug 8 at 2:46
  • 1
    @Mass true, but not sure what to do against it, the whole point of adding gn was to be able to select the current word, if it matches. In any case, it might help to explicitly add \C to the pattern so that the 'ignorecase' setting does not apply. – Christian Brabandt Aug 8 at 14:51

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.