如何在 Vim 中使用基于计数器的表达式进行搜索和替换? [英] How to search and replace with a counter-based expression in Vim?

查看:17
本文介绍了如何在 Vim 中使用基于计数器的表达式进行搜索和替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Vim :substitute 命令中插入某种计数器变量的值?

Is there a way to insert the value from some sort of counter variable in Vim :substitute command?

例如,要转换此文档:

<SomeElement Id="F" ... />
<SomeElement Id="F" ... />
<SomeElement Id="F" ... />

到这个结果文件:

<SomeElement Id="1" ... />
<SomeElement Id="2" ... />
<SomeElement Id="3" ... />

我想,命令看起来像这样:

I imagine, the command would look like so:

:%s/^(s*<SomeElement Id=")F(".*)$/1<insert-counter-here>2/g

我使用的是最新的 Windows 版本,来自他们提供的安装程序.我强烈不希望安装任何额外的工具.理想情况下,我还想避免安装脚本来支持这一点,但如果这是唯一的方法,我愿意这样做.

I am using a very recent Windows build, from their provided installer. I strongly prefer not to install any additional tools. Ideally, I'd like to also avoid having to install scripts to support this, but I'm willing to, if it is the only way to do it.

推荐答案

Vim wiki 说明 似乎成为最简单的解决方案(至少对我而言).

Vim wiki instructions seems to be the easiest solution (at least for me).

以下示例将所有出现的 PATTERN 替换为 REPLACE_[counter](REPLACE_1REPLACE_2 等):

Example below replaces all occurences of PATTERN with REPLACE_[counter] (REPLACE_1, REPLACE_2 etc.):

:let i=1 | g/PATTERN/s//='REPLACE_'.i/ | let i=i+1

要回答这个问题,它可能看起来像这样:

To answer the question it might look like this:

:let i=1 | g/SomeElement Id="F"/s//='SomeElement Id="'.i.'"'/ | let i=i+1

替代方案

如果有人对使用 %s 语法的解决方案感兴趣,我建议查看@ib.答案是:

Alternative solution

If anyone is interested in a solution with %s syntax I would advise to look at the @ib. answer which is:

:let n=[0] | %s/Id="zsFze"/=map(n,'v:val+1')/g

这篇关于如何在 Vim 中使用基于计数器的表达式进行搜索和替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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