Vim, find the n'th occurence of a word

时间:2015-10-30 23:55:50

标签: linux vim

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?

2 个答案:

答案 0 :(得分:1)

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

它会将myWord的第6次出现替换为newWord。

答案 1 :(得分:0)

Gnu-sed 这不是问题的答案:它只是改变第n次出现的另一种方式。要获得正确的答案,请参阅@ sureshkumar的回答和@ lurker的评论。

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

其中:

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