如何复制与模式匹配的行,并在一个命令中修改第二行? [英] How can I duplicate lines matching a pattern, and modify the second line, all in one command?
问题描述
我正在尝试向 Java 类添加一个属性,使用 VIM 作为编辑器.因此,我认为我可以使用一个命令来简化所有样板代码的工作.例如:
I'm trying to add an attribute to a java class, using VIM as the editor. Therefore I thought I could use a command to ease my work with all the boilerplate code. Eg:
所有包含atributeA"的行,就像这个
All lines containing "atributeA", like this one
this.attributeA=attributeA //basic constructor
应该变成
this.attributeA=attributeA //basic constructor
this.attributeB=attributeB //basic constructor
有可能吗?
推荐答案
使解决方案像需求一样是单行的有点奇怪,因为您可以分配任何序列击键或任何功能或命令到 Vim 中的按键如果你喜欢.
Having the solution be a one-liner as a requirement seems a little odd, since you can assign any sequence of keystrokes or any function or command to a keypress in Vim if you like.
话虽如此,这种类型的东西是 Vi 的面包和黄油.试试:
That being said, this type of thing is Vi's bread and butter. Try:
:g/attributeA/ copy . | s//attributeB/g
哪里
:g/pattern/ command1 | command2 | ...
在匹配pattern
的每一行上执行命令(参见:help :global
),
executes commands on each line matching pattern
(see :help :global
),
copy .
将与:g
匹配的当前行(见:help :copy
)复制到地址之后.
(表示当前行), 和
copies the current line (see :help :copy
) matched by :g
to after the address .
(meaning the current line), and
s/pattern/replacement/g
然后在当前行上执行替换(参见 :help :substitute
),即你刚刚制作的副本.末尾的 g
标志导致对行中所有匹配模式执行替换,而不仅仅是第一个.另请注意,我将搜索模式留空:为了方便起见,Vim 会记住上一个 :global
或 :substitute
命令中使用的最后一个搜索模式.
then performs a substitution on the current line (see :help :substitute
), i.e. the copy you just made. The g
flag at the end causes the substitution to be performed for all matching patterns in the line, not just the first. Also note that I left the search pattern empty: Vim will remember the last search pattern used in the previous :global
or :substitute
command as a convenience.
这篇关于如何复制与模式匹配的行,并在一个命令中修改第二行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!