How to replace contents within quotes for several rows

Viewed 51

I have this code:

System.out.println("plant");
System.out.println("tree");
System.out.println("grass");
System.out.println("flower");

and I want to replace the content within "" with the following content, where one line contains one word in a text editor:

animal
dog
fish
elephant

What I want is:

System.out.println("animal");
System.out.println("dog");
System.out.println("fish");
System.out.println("elephant");

I've tried column editing and did not get the expected result.

Is there any trick that can do this in a simple way?

3 Answers

You can do the inverse and add System.out.println(" and "); around every word in the words file by using search and replace with a regular expression that matches the entire line:

:%s/^\(.*\)$/System.out.println("\1");

Then you can move that section to the source file.

Or you move the words to the source file first and then do the search and replace operation there, just not for the entire file, but only for a visual line selection (Shift+v) containing the words. To do that, you need to change :% to :'<,'> in the command.

You don't need to type '<,'>, it will be inserted automatically when you enter : while in visual line selection mode.

What you could do also is to record a macro on the second file (the one with animal, dog, fish, elephant).

What you need to do is put the cursor on the first line (before word animal), type "qa" in normal mode (esc) - this will start recording a macro in register "a".

Then go to insert mode, type System.out.println(", stop before "animal", type ESC to go to normal mode, then $ to move to the last character in line, then i to enter insert mode and type "); after animal. Finally type ESC and q to finish recording the macro.

Then for each of the lines, you can execute the macro by typing @a. Or you can launch it on each line by executing this command:

:g/^/norm!@a

To learn more about VIM macros: https://vim.fandom.com/wiki/Macros

I've got a good answer shown as the gif picture, using macros and split screen in Vim. This answer comes from kidneyball in ZhiHu (a Chinese website).

If you want to see more solutions go to this page, https://www.zhihu.com/question/419191791?group_id=1284909403133231104, scroll down, and you will see many pictures, you need not to know about Chinese, just see the key logs performed on each picture.

the solution with key logs, refers to ZhiHu kidneyball

Related