I want to insert subsequent numbers whenever there a regex matches.

I do this in terminal using for command and either perl or sed.

Is there a way to do this in vim?

Basically I want this:

 This is a command

To turn to this:

 This is a1 comma2nd

where I am using the regex a

  • 1
    If you have a command that reads a file from stdin and outputs it to stdout, named addMatchNumbers that takes as its first argument the regex, you could use vim filters : eg write :%! addMatchNumbers a
    – edi9999
    Commented Sep 17, 2015 at 12:01

1 Answer 1


One way:

let g:i = 0
function! Increment()
    let g:i = g:i + 1
    return g:i

And then:

:%s/pattern/\=submatch(0) . Increment()/g

BTW, this question is pretty similar.

  • Or just :%s/pattern\zs/\=Increment()/g. Exercise to the astute reader: make Increment() reset the counter at the beginning of each line, rather than count occurrences from the beginning of file. Commented Sep 18, 2015 at 6:47
  • Nice :) (To reset counter, I'd rather use :global with let g:i = 0 followed by a similar substitution on current matching line).
    – VanLaser
    Commented Sep 18, 2015 at 7:41

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.