简体   繁体   English

VIM全局多行搜索和替换维护缩进

[英]VIM global multiple line search and replace maintaining indent

I am trying to perform a multiple line search and replace while retaining the indent, leading space, in the code I am working with. 我正在尝试执行多行搜索并替换,同时在要使用的代码中保留缩进的前导空格。 Below is a text sample which approximates the situation. 以下是近似情况的文本示例。 The problem I'm having is preserving the white space. 我遇到的问题是保留空白。 I'm hoping for a non-plugin, plain jane VIM solution via :%s/ ...... 我希望通过:%s / ......提供一个非插件的简简VIM解决方案。

VIM 7.2 on Windows 7 autoindent is on expandtab is on Windows 7上的VIM 7.2自动缩进已打开expandtab已打开

Starting with: 从...开始:

  apples,
  banannas,
  cherries,
  plums

  peas,
  green beans,
  corn,
  squash

        apples,
        banannas,
        cherries,
        plums

I would like to add "pears,", without the double quotes and following the "cherries," line in the list. 我想添加“豌豆”,不带双引号,并在列表中的“樱桃”行之后。 The desired outcome is: 理想的结果是:

  apples,
  banannas,
  cherries,
  pears,
  plums

  peas,
  green beans,
  corn,
  squash

        apples,
        banannas,
        cherries,
        pears,
        plums

Trying :%s/cherries,/&\\rpears,/g yields ... 尝试:%s /樱桃,/&\\梨,/ g产量...

      apples,
      banannas,
      cherries,
pears,
      plums

      peas,
      green beans,
      corn,
      squash

            apples,
            banannas,
            cherries,
pears,
            plums

Trying :%s/cherries,_s.\\s*/&pears,\\r/g yields ... 尝试:%s / cherry,_s。\\ s * /&pears,\\ r / g产生...

      apples,
      banannas,
      cherries,
      pears,
plums

      peas,
      green beans,
      corn,
      squash

            apples,
            banannas,
            cherries,
            pears,
plums

Thank you! 谢谢!

您可以利用:g和带有普通o自动缩进功能:

:g/cherries,/normal opears,

Try to extract the whitespace just before the word and insert it in the replacement part ( \\1 ). 尝试提取单词之前的空白并将其插入替换部分( \\1 )。

NOTE that I use \\v at the beginning but it does not match anything, it is to make the regular expression very magic and avoid to escape many characters, like parentheses. 请注意 ,我在开始时使用\\v ,但它与任何内容都不匹配,这是为了使正则表达式非常神奇,并避免转义许多字符,例如括号。

:%s/\v(\s*)cherries,/&\r\1pears,/g

It yields: 它产生:

  apples,
  banannas,
  cherries,
  pears,
  plums

  peas, 
  green beans,
  corn,
  squash

        apples,
        banannas,
        cherries,
        pears,
        plums

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM