在Vim中,如何搜索和替换所有其他匹配项? [英] In Vim how can I search and replace every other match?
问题描述
说我有以下文件
<block>
<foo val="bar"/>
<foo val="bar"/>
</block>
<block>
<foo val="bar"/>
<foo val="bar"/>
</block>
我如何将其变成
<block>
<foo val="bar1"/>
<foo val="bar"/>
</block>
<block>
<foo val="bar1"/>
<foo val="bar"/>
</block>
我尝试做的一件事是用记录宏:%s / bar / bar1 / gc
并分别按 y
和 n
一次,然后尝试编辑该宏。由于某些原因,我无法编辑宏。 :(
One thing I tried to do was record a macro with :%s/bar/bar1/gc
and press y
and n
once each and then try to edit that macro. For some reason I cannot edit the macro. :(
推荐答案
仅显示可以用替代方法完成:
Just to show that this can be done in a substitution:
:let a = ['', '1']
:%s/bar\zs/\=reverse(a)[0]/g
概述
在末尾替换每个 bar
中,数组的第一个元素位于变量 a
中,此数组在每次替换后都就地反转。 / p>
荣耀之光
Overview
Replace at the end of every bar
with the first element of array in variable a
after the array is reversed in-place upon every substitution.
-
让a = [' ','1']
定义变量a
来保存数组 -
%s /.../.../
对文件中的每一行进行替换 -
%s / bar\ \zs /.../
在bar上进行替换,但使用\zs
-
\ =
使用以下表达式的值 -
reverse(a)
反向简单地反转数组,但在行内这样做e -
reverse(a)[0]
反向返回现在反向的数组,因此获取第一个元素 -
/ g
替换行中的所有事件(可选)
在bar之后开始替换在
:s
命令的替换部分内的let a = ['', '1']
define an variablea
to hold our array%s/.../.../
do a substitution on every line in the file%s/bar\zs/.../
do a substitution on bar but start the replacement after bar using\zs
\=
inside the replacement portion of the:s
command uses the value of the following expressionreverse(a)
reverse simply reverses the array, but does so in-placereverse(a)[0]
reverse returns the now reversed array so get the first element/g
replace all occurances in the line (optional)
一般情况
General Case
:let a = ['a', 'b', 'c']
:%s/bar\zs/\=add(a, remove(a, 0))[-1]/g
一般情况下,将数组 a
就地旋转,并使用数组的最后位置作为替换替换的值。
The general case "rotates" the array, a
, in-place and uses the last position of the array as the value for the replacement of the substitution.
有关更多帮助,请参见
:h :s
:h range
:h /\zs
:h :s\=
:h reverse(
:h :s_flags
:h Lists
:h add(
:h remove
这篇关于在Vim中,如何搜索和替换所有其他匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!