繁体   English   中英

vim:找到一个模式,跳过一个单词,然后在所有匹配的行中附加一些内容

[英]vim : Find a pattern, skip a word and append something in all matching lines

我知道vim中的简单搜索和替换命令(:%s/apple/orange/g)在其中找到所有“苹果”并将其替换为“橙色”。

但是可以在vim中做这样的事情吗? 在跳过下一个单词(如果有)之后找到文件中的所有“小麦”并追加“存储”?

示例:原始文件内容:

Wheat flour
Wheat bread
Rice flour
Wheat

搜索并替换后:

Wheat flour store
Wheat bread store
Rice flour
Wheat store

这是使用global命令的最佳时机。 它将对与给定正则表达式匹配的每一行应用命令。

                        *:g* *:global* *E147* *E148*
:[range]g[lobal]/{pattern}/[cmd]
            Execute the Ex command [cmd] (default ":p") on the
            lines within [range] where {pattern} matches.

在这种情况下,命令为norm A store ,而正则表达式为wheat 综上所述,我们拥有

:g/Wheat/norm A store

现在,您可以使用replace命令执行此操作,但是我发现global更加方便和易读。 在这种情况下,您将拥有:

:%s/Wheat.*/& store

意思是:

:%s/                " On every line, replace...
    Wheat           "   Wheat
         .*         "   Followed by anything
           /        " with...
            &       "   The entire line we matched
              store "   Followed by 'store'

暂无
暂无

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

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