Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

vi

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:

All lines containing "atributeA", like this one

this.attributeA=attributeA //basic constructor

should turn into

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

Is it possible?

like image 624
sdaniel Avatar asked Dec 24 '22 21:12

sdaniel


1 Answers

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.

That being said, this type of thing is Vi's bread and butter. Try:

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

where

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

executes commands on each line matching pattern (see :help :global),

copy .

copies the current line (see :help :copy) matched by :g to after the address . (meaning the current line), and

s/pattern/replacement/g

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.

like image 150
1983 Avatar answered Dec 28 '22 18:12

1983