1

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.

8
  • :%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
    Commented Jul 13, 2018 at 14:00
  • @statox No. :%s//\U\1/g doesn't work. It simply deletes all the values matching the last searched pattern.
    – shivams
    Commented Jul 13, 2018 at 14:01
  • 2
    Instead of \1, use & (or \0, which is the same) Commented Jul 13, 2018 at 14:30
  • @LucHermitte : You nailed it!! This is certainly fast. Please post this as answer.
    – shivams
    Commented Jul 13, 2018 at 14:34
  • Well, statox had the solution, but he missed the unneeded group :) Commented Jul 13, 2018 at 14:37

2 Answers 2

3

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
4

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).

12
  • Wow. That is one creative solution. However, . doesn't work here. Can you clarify?
    – shivams
    Commented Jul 13, 2018 at 16:43
  • Works for me, maybe your vim is too old?
    – Mass
    Commented Jul 13, 2018 at 18:20
  • 1
    Or g~ to actually invert the case
    – D. Ben Knoble
    Commented Jul 13, 2018 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
    Commented Aug 8, 2018 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. Commented Aug 8, 2018 at 14:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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