Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

marked as duplicate by Michael Mrozek Feb 26 '12 at 19:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
Just a note: the linked question restricts the occurrences to a single line whereas this question seems to be asking about the whole file. However the same techniques would apply by simply prepending a range of % to any :s command in any of the answers there. –  jw013 Jan 24 '12 at 16:24

3 Answers 3

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
share|improve this answer
    
@Kevin thanks. I was thinking one thing and typed another. I've corrected my answer replacing . with n. –  Stephen Quan Feb 14 '12 at 2:11
    
Yep, that'll work. Not to nag, but / [and n for that matter] takes an argument, so 5/hello will find the fifth occurrence of hello. –  Kevin Feb 14 '12 at 2:16
    
@Kevin thanks, yeah, you're right. You beat me to it as I was just looking that up. –  Stephen Quan Feb 14 '12 at 2:19

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.

share|improve this answer
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

before

word
word
word
word
word
word
word

after

hello
hello
bonjour
bonjour
bonjour
namaste
namaste
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.