Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 260
awllower Avatar asked Aug 29 '16 04:08

awllower


2 Answers

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()/
like image 102
Luc Hermitte Avatar answered Oct 23 '22 03:10

Luc Hermitte


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.

like image 2
SibiCoder Avatar answered Oct 23 '22 04:10

SibiCoder