basically I have a bunch of lines of code that all match the format .\module.variable (), .\module.variable2 (),

I want to take everything between the backslash and the space, before the parentheses and put it in the parentheses for each line, with whatever is on that line, like this: .\module.variable (module.variable), .\module.variable2 (module.variable2),


Visit each line that has the key pattern using the global command and do a (global) substitution on that same pattern at each visited line:

:g/\.\\\(\S\+\) ()/ s//.\\\1 (\1)/g

The pattern, which is used in both the global and substitution operations:

  • \.\\ : period and backslash
  • \(\S\+\) : non-empty, non-space string inside a capturing group (\(...\)) which allows us to reference the match in the replacement section of the substitution operation
  • () : a space and empty pair of parens

We leave the pattern in the substitution operation empty which indicates that we want the last used pattern. The replacement part then just uses the capturing group back reference (\1) twice to build the target string. (Note: I don't think Vim help refers to these constructs as "capture/capturing groups" but it's pretty much a universally used term for them.)

  • Couldnt you do this with %s/the messy pattern/the repl/g ? Why invoke global?
    – D. Ben Knoble
    Sep 29 '19 at 17:28
  • Of course you can but there's no significant upside to doing so and its not very interesting (everyone knows plain :s) while mine is more likely to expand a newer user's skill set (without being an unrealistic approach) and that possibility is one of the main reasons I do this. If I were teaching a bunch of professionals who planned to use this on huge amounts of text I'd probably have done differently but that's not what's going on here.
    – B Layer
    Sep 29 '19 at 20:17
  • Plus there are already so many posts here that are just glorified regex questions and the banner says Vi/Vim. Plus...well you get the point.
    – B Layer
    Sep 29 '19 at 20:27
  • What would you have said to a bunch of professionals using this on huge amounts of text?
    – SpaceRace
    Sep 30 '19 at 15:00
  • "Use sed". But seriously if someone insisted on using vim/ex to do big batches of find/replace I'd tell them to use whatever I found to be the fastest performer based on some relevant benchmarking/testing.
    – B Layer
    Oct 1 '19 at 1:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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