如何在一个命令中复制与模式匹配的行并修改第二行?

How can I duplicate lines matching a pattern, and modify the second line, all in one command?

我正在尝试将属性添加到 java class,使用 VIM 作为编辑器。 因此,我认为我可以使用命令来简化所有样板代码的工作。 例如:

所有包含 "atributeA" 的行,比如这一行

this.attributeA=attributeA //basic constructor

应该变成

this.attributeA=attributeA //basic constructor
this.attributeB=attributeB //basic constructor

可能吗?

您的确切示例很容易通过以下方式实现:

yy
p
:s/A/B/g

但您完全有可能想要更通用的东西。如果是这种情况,您可能应该编辑您的问题。

看看这个函数:

function AddAttribute()
    exe "/this.attributeA=attributeA;"
    exe "normal yyp"
    exe "s/attributeA/" . input('New attribute: ') . "/g"
endfunction

当您调用函数 call AddAttribute() 时,系统会提示您输入一个新属性,该属性将像您的示例中那样添加。您可以为此绑定一个键,例如 :map <F5> :call AddAttribute<CR> 这样您只需按 F5 即可添加此行。

编辑

如果你想用 attributeA 复制所有行(这对我来说没有意义),你可以用这个映射来做到这一点(^MCTRL+v然后输入):

:map <F5> :call inputsave()\|let newAttribute=input('new attribute: ')\|:call inputrestore()\|:g/attributeA/exe "normal! yyp"\|exe ":s/attributeA/" . newAttribute . "/g"^M

当您点击 F5 时,系统会提示您输入新属性,并且包含 attributeA 的所有行都会被复制并替换为您的输入。

似乎要求解决方案是单行的 有点奇怪,因为你可以分配任何序列 Vim 中的击键或按键的任何功能或命令 如果你喜欢。

也就是说,这类东西是 Vi 的生计。尝试:

:g/attributeA/ copy . | s//attributeB/g

哪里

:g/pattern/ command1 | command2 | ...

在匹配 pattern 的每一行上执行命令(参见 :help :global),

copy .

:g匹配的当前行(见:help :copy)复制到地址.(即当前行)之后,并且

s/pattern/replacement/g

然后在当前行执行替换(参见 :help :substitute),即您刚刚制作的副本。末尾的 g 标志导致对行中所有匹配模式执行替换,而不仅仅是第一个。另请注意,我将搜索模式留空:Vim 会记住之前 :global:substitute 命令中使用的最后一个搜索模式,以方便使用。