Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform search & replace using a callback command

Tags:

vim

I'm trying to search & replace inside my file for all occurrences of a particular pattern, then call toupper() on each match. In practice, there aren't that many occurrences that I couldn't just do this by hand, but I'm curious to improve my Vim skills and find a (simple) way to get Vim to do this for me. I say simple, otherwise I'll just forget.

From a read over the Vim help for s/, I should be able to do something like this:

:%s/\vfunction ([a-z0-9_]+)/\="function " . toupper("\1")/g

(Assuming I'm uppercasing all function definition names).

This actually just replaces the function names with the control character ^A though. How do I refer to the capturing group in the regexp?

like image 979
d11wtq Avatar asked May 11 '26 09:05

d11wtq


1 Answers

Apologies. I should read more closely. I'll answer my own question anyway, instead of deleting it. You need to use submatch(n) to refer to the capturing group:

:%s/\vfunction ([a-z0-9_]+)/\="function " . toupper(submatch(1))/g
like image 133
d11wtq Avatar answered May 14 '26 01:05

d11wtq