替换 vim 中第 n 次出现的单词 [英] Substitute the n-th occurrence of a word in vim

查看:40
本文介绍了替换 vim 中第 n 次出现的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了其他有关查找单词/模式的第 n 次出现的问题,但我找不到如何在 vim 中实际替换模式的第 n 次出现.有明显的硬编码方法,如

I saw other questions dealing with the finding the n-th occurrence of a word/pattern, but I couldn't find how you would actually substitute the n-th occurrence of a pattern in vim. There's the obvious way of hard coding all the occurrences like

:s/.*\(word\).*\(word\).*\(word\).*/.*\1.*\2.*newWord.*/g 

有没有更好的方法来做到这一点?

Is there a better way of doing this?

推荐答案

您可以通过使用多个搜索更简单地完成此操作.:s/pattern/repl/ 命令中的空模式表示替换最近的搜索结果.

You can do this a little more simply by using multiple searches. The empty pattern in the :s/pattern/repl/ command means replace the most recent search result.

:/word//word//word/ s//newWord/
or
:/word//word/ s/word/newWord/

然后您可以通过执行 @: 或什至 10@: 将命令重复 10 次以上来重复此操作.

You could then repeat this multiple times by doing @:, or even 10@: to repeat the command 10 more times.

或者,如果我以交互方式执行此操作,我会执行以下操作:

Alternatively, if I were doing this interactively I would do something like:

3/word
:s//newWord/r

这将找到从光标开始的第三次出现的 word 然后执行替换.

That would find the third occurrence of word starting at the cursor and then perform a substitution.

这篇关于替换 vim 中第 n 次出现的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆