awllower
awllower

Reputation: 571

Is it possible to mark the n-th occurrence of a pattern with n in vim?

Say I have a text like the following.

The man is walking, and the man is eating.

How should I use substitution to convert it to the following?

The man 1 is walking, and the man 2 is eating.

I know I can use :%s/\<man\>//gn to count the number of occurrences of the word man and I know /\%(\(pattern\).\{-}\)\{n - 1}\zs\1 can find the n-th occurrence of pattern. But how do I mark the n-th occurrence?

Any help is sincerely appreciated; thanks in advance.

Upvotes: 5

Views: 108

Answers (2)

SibiCoder
SibiCoder

Reputation: 1496

You can do that with a macro. First, search for the pattern, like /man /e.

Let's create a variable for count, like :let cnt=1.

Now, let's clear the a register.

Start recording by pressing qa.

Press n.

Press i, then, Ctrl+R type =. Type cnt. Value of count is inserted there. Then, type :let cnt=cnt+1.

Press Escape.

Press q to stop the register.

Now, type :%s/man //gn to get number of occurrences.

Now, you know the number of occurences, say 10. Then, you will press 10@a. All the occurrences will be appended with a number, which is incremented for every occurrence.

Upvotes: 2

Luc Hermitte
Luc Hermitte

Reputation: 32926

You'll need to have a non-pure function that counts occurrences, and use the result of that function.

" untested
let s:count = 0
function! Count()
    let s:count += 1
    return s:count
endfunction

:%s/man\zs/\=' '.Count()/

Upvotes: 6

Related Questions