vim:找到一个模式,跳过一个单词并在所有匹配的行中附加一些东西

Dar*_*zen 0 regex vim pattern-matching

我知道(:%s/apple/orange/g)在vim中的简单搜索和替换命令,我们找到所有'苹果'并用'orange'替换它们.

但是有可能在vim中做这样的事情吗?在文件中找到所有'Wheat'并在跳过下一个单词后添加"store"(如果有的话)?

示例:原始文件内容:

Wheat flour
Wheat bread
Rice flour
Wheat
Run Code Online (Sandbox Code Playgroud)

搜索和替换后:

Wheat flour store
Wheat bread store
Rice flour
Wheat store
Run Code Online (Sandbox Code Playgroud)

DJM*_*hem 5

这是使用该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.
Run Code Online (Sandbox Code Playgroud)

在这种情况下,命令是norm A store和正则表达式wheat.所以把它们放在一起,我们有

:g/Wheat/norm A store
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用substitute命令执行此操作,但我发现global更方便,更易读.在这种情况下,你有:

:%s/Wheat.*/& store
Run Code Online (Sandbox Code Playgroud)

意思是:

:%s/                " On every line, replace...
    Wheat           "   Wheat
         .*         "   Followed by anything
           /        " with...
            &       "   The entire line we matched
              store "   Followed by 'store'
Run Code Online (Sandbox Code Playgroud)