VIM: Finding and replacing first N occurrences of a word

我怕爱的太早我们不能终老 提交于 2019-11-29 03:01:07

问题


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/

:%s/word/newword/count

And other commands that i could find on google. But none of them works.

EDIT:: Vim commands is preferred. But Vim script can also be used. I don't have any prior experience in vim scripting.


回答1:


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@:



回答2:


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.




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/25840580/vim-finding-and-replacing-first-n-occurrences-of-a-word

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!