在Vim中搜索并替换为基于计数器的表达式 [英] Search and replace with a counter-based expression in Vim

查看:74
本文介绍了在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_1 REPLACE_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="\zsF\ze"/\=map(n,'v:val+1')/g

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

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