steve_gallagher
steve_gallagher

Reputation: 3888

VIM: Select a regex, then apply a command

I want to change a large group of identifiers from lower-case to upper-case. I have a file with a number (hundreds or so) of unique identifiers that start with a q_. I constructed a regex that defines this match: (q_\w*) and now I want to apply the ~ command to make them all upper-case (they are currently lower-case). I feel like VIM is more than capable of doing this but my skill with it is not there yet, can you help?

Upvotes: 5

Views: 513

Answers (2)

pb2q
pb2q

Reputation: 59607

If you want to up-case the entire identifier, for each identifier in the file, use this substitute command:

%s/q_\w\+/\U&/g

The trick here is & in the replacement pattern, which references the entire match. This will substitute e.g. q_identifier1 with Q_IDENTIFIER1.

If you only want to up-case the q, then you can use:

%s/q_\(\w\+\)/Q_\1/g

Now q_identifier1 will be changed to: Q_identifier1

If you want to up-case everything except the q_, then use:

%s/q_\(\w\+\)/q_\U\1/g

Now q_identifier1 will be changed to: q_IDENTIFIER1

Upvotes: 6

none
none

Reputation: 12087

you can also use a macro for this purpose:

  • search your pattern: /q_\w*
  • start recording a macro: qq
  • make uppercase and find next: llve~n
  • stop recording your macro: q
  • repeat as neccessary: 666@q

but nothing more or it will wrap and change back to lowercase (or alternatively you can turn off wrapscan or ignorecase temporarily).

Upvotes: 0

Related Questions