VIM: Finding and replacing first N occurrences of a word

前端 未结 4 1411
一向
一向 2020-12-28 08:39

I am editing a file and i want to change only a specific word with another word, but only for first N occurrences. I tried multiple commands

N :s/word/newword/

相关标签:
4条回答
  • 2020-12-28 08:58

    Using a disposable recording allows you to control exactly how many changes you do:

    qq             " start recording in register q
    /foo<CR>       " search for next foo
    cgnbar<Esc>    " change it to bar
    q              " end recording
    11@q           " play recording 11 times
    

    See :help recording and :help gn.

    Another way, using :normal:

    :norm! /foo<C-v><CR>cgnbar<C-v><Esc>     <-- should look like this: :norm! /foo^Mcgnbar^[
    11@:
    

    See :help :normal and :help @:.

    Or simply:

    :/foo/|s//bar<CR>
    11@:
    
    0 讨论(0)
  • 2020-12-28 09:06

    I'm not sure about specifying the first N occurrences, but I often use this command:

    :%s/word/newword/gc
    

    Vim then asks for confirmation of each occurrence of word so you can selectively change some but not others.

    0 讨论(0)
  • 2020-12-28 09:16

    Although a bit longer, you can do:

    :call feedkeys("yyyq") | %s/word/newword/gc
    

    to replace the first 3 occurrences and then stop. You can change the amount of y's for more or less replacements. (Can also use n to skip some)

    Explanation: this is feeding y keystrokes into the /c confirm option of the substitution command.

    0 讨论(0)
  • 2020-12-28 09:17

    My PatternsOnText plugin provides (among many others) a command that takes answers in the form of either yyynyn or 1-5:

    :%SubstituteSelected/word/newword/g 1-5
    
    0 讨论(0)
提交回复
热议问题