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.
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()/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With