2

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?

  • 5
    (1) Open the file with `vim`, (2) type `6/myWord`, then (3) press Enter. In the visual mode, entering a number followed by a command executes that command that number of times. So this executes `/myWord` 6 times, which finds the 6th occurrence of `myWord`. – lurker Oct 30 '15 at 23:57

2 Answers2

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

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

  • cool!! (+1) but: it replaces the 7th oco in the same line. `:1s/\v%((myWord)\_.{-}){5}\zs\1/newWord/ ` – JJoao Nov 02 '15 at 13:41
1

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
JJoao
  • 4,891
  • 1
  • 18
  • 20
  • Please read the question carefully. The question in in vim editor we have to replace not in command line. –  Nov 02 '15 at 15:17
  • @sureshkumar, it was not meant to be a proper answer... (I added a disclaimer aout it). Of course we can: `:%!sed -z s/myWord/newWord/6` – JJoao Nov 02 '15 at 15:35
  • @sureshkumar: tahnk you. Again you are right. Added a note -- just in gnu sed. – JJoao Nov 03 '15 at 08:29
  • 1
    Thank you @JJoao, I was looking for a solution to do the replace using vim, this is how I got to this page. Your answer is much better. People using vim are most probably also comfortable with the command line. I had to replace the 5th occurance of a separator and remove it on each line. So I this without the -z. Works perfectly! – Ami Heines Jul 04 '19 at 07:42