如何在VI/VIM编辑器中用每次出现的不同单词替换查找单词? [英] How to replace finding words with the different in each occurrence in VI/VIM editor ?

查看:69
本文介绍了如何在VI/VIM编辑器中用每次出现的不同单词替换查找单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一条文字,10 3 4 2 10,4,10 ....

For example, I have a text , 10 3 4 2 10 , 4 ,10 ....

不,我想用不同的单词每10个更改

No I want to change each 10 with different words

我知道%s/10/replace-words/gc,但它只允许我像是/否那样以交互方式进行替换,但是我想用不同的词(例如replace1、3、4、2,replace2、4)更改每次出现的10,replace3 ....

I know %s/10/replace-words/gc but it only let me replace interactively like yes/no but I want to change each occurrence of 10 with different words like replace1, 3, 4 , 2 , replace2, 4, replace3 ....

推荐答案

将每次出现的 10 替换为 replace {index_of_match} :

:let @a=1 | %s/10/\='replace'.(@a+setreg('a',@a+1))/g

用预定义数组中的单词替换每次出现 10 :

Replaces each occurence of 10 with a word from a predefined array:

:let b = ['foo', 'bar', 'vim'] | %s/10/\=(remove(b, 0))/g

用预定义数组中的单词和匹配的索引替换每次出现 10 的情况:

Replaces each occurence of 10 with a word from a predefined array, and the index of the match:

:let @a=1 | let b = ['foo', 'bar', 'vim'] | %s/10/\=(b[@a-1]).(@a+setreg('a',@a+1))/g

但是由于无论如何您都必须输入任何单词,第二个和第三个函数的好处是微不足道的.有关手动"解决方案,请参见SpoonMeiser的答案.

But since you have to type in any word anyway, the benefit of the second and third function this is minimal. See the answer from SpoonMeiser for the "manual" solution.

更新:如所希望的,第二个示例中对正则表达式部分的解释:

Update: As wished, the explanation for the regex part in the second example:

=
s/< search>/< replace>/g = s 表示执行搜索&替换, g 表示替换所有情况.
\ = 将以下内容解释为代码.
remove(b,0)删除列表 b 的索引0处的元素,并将其返回.

%= on every line in the document
s/<search>/<replace>/g = s means do a search & replace, g means replace every occurence.
\= interprets the following as code.
remove(b, 0) removes the element at index 0 of the list b and returns it.

所以是第一次出现.该行第二次为%s/10/foo/g ,该列表现在仅为 ['bar','vim'] ,因此该行将为<代码>%s/10/bar/g 等

so for the first occurrence. the line will be %s/10/foo/g the second time, the list is now only ['bar', 'vim'] so the line will be %s/10/bar/g and so on

注意:这是快速草稿,不太可能是最好的&实现这一目标的最简洁的方法,如果有人想对其进行改进,请随时添加评论

这篇关于如何在VI/VIM编辑器中用每次出现的不同单词替换查找单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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