Timothy Walker
Timothy Walker

Reputation: 73

Vim, find the n'th occurence of a word

I tried using the following syntax, in Vim to find the n'th occurence of a word(i would like to replace that word with another one)

:6:myWord 

and I would like to replace it with newWord

I do not understand what I am getting wrong, can anybody help me?

Upvotes: 2

Views: 4837

Answers (2)

JJoao
JJoao

Reputation: 5347

Gnu-sed This is not an answer to the question: it is just an alternative way of changing the n'th occurence. For a proper answer see @sureshkumar's answer and @lurker's comment.

sed -z -i.bak s/myWord/newWord/6  file

where:

-i.bak    infile editing (creating file.bak as a bakup)
-z        null separeted registers (all file = one register) (gnu sed)
/6        6'th occurence

Upvotes: 1

user5076313
user5076313

Reputation:

s/\%(\(myWord\).\{-}\)\{6}\zs\1/newWord/
           ^             ^             ^
            Pattern       Occurrence    Replace pattern

It will replace the 6th occurrence of a myWord to newWord.

Upvotes: 1

Related Questions