Possible Duplicate:
Vim :s replace first N < g occurrences on a line
In vi, how do I search and replace a word's first n occurrences with a word, say "hello", and the next m occurrences with bonjour, and all the rest with namaste?
Possible Duplicate:
Vim :s replace first N < g occurrences on a line
In vi, how do I search and replace a word's first n occurrences with a word, say "hello", and the next m occurrences with bonjour, and all the rest with namaste?
Can you locate the nth "hello" manually? If so, then, I would locate the nth hello as follows:
:1 (goes to the first line of your file)
n/hello (find the nth hello, where n is the number)
Then substitute all the hellos as follows:
:1,.s/hello/bonjour/g
(move to the next line)
:.,$s/hello/namaste/g
This basically boils down to the same as my question (linked in the comments; as mentioned, mine asks about a single line but is trivially generalized to more). The easiest answer is :%s/hello/first/gc, hit y n times and then q, :%s/hello/second/gc, y m times and q, etc. If you need more than a few, use feedkeys and repeat as outlined in the accepted answer there.
fun! FUN(n, m)
if !exists('g:count')
let g:count = 0
endif
let g:count+=1
if g:count<=a:n
return 'hello'
elseif g:count<=a:n+a:m
return 'bonjour'
else
return 'namaste'
endif
endfun
:unlet! g:count
:%s/word/\=FUN(2, 3)/g
word
word
word
word
word
word
word
hello
hello
bonjour
bonjour
bonjour
namaste
namaste