在Vim中,如何搜索和替换所有其他匹配项? [英] In Vim how can I search and replace every other match?

查看:285
本文介绍了在Vim中,如何搜索和替换所有其他匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下文件

<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.


  1. 让a = [' ','1'] 定义变量 a 来保存数组

  2. %s /.../.../对文件中的每一行进行替换

  3. %s / bar\ \zs /.../在bar上进行替换,但使用 \zs

  4. 在bar之后开始替换在:s 命令的替换部分内的
  5. \ = 使用以下表达式的值

  6. reverse(a)反向简单地反转数组,但在行内这样做e

  7. reverse(a)[0] 反向返回现在反向的数组,因此获取第一个元素

  8. / g 替换行中的所有事件(可选)

  1. let a = ['', '1'] define an variable a to hold our array
  2. %s/.../.../ do a substitution on every line in the file
  3. %s/bar\zs/.../ do a substitution on bar but start the replacement after bar using \zs
  4. \= inside the replacement portion of the :s command uses the value of the following expression
  5. reverse(a) reverse simply reverses the array, but does so in-place
  6. reverse(a)[0] reverse returns the now reversed array so get the first element
  7. /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屋!

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