Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching for string while recording a macro in VIM

Tags:

vim

macros

I want to add a new field to objects in a list using vim. Each object is not the same number of lines. However, the last field is the same for each object.

The new field is the same for each object, so I figured I could create a vim macro that would insert the static field at the end of each object, as well as inserting a comma on the preceding line. My problem is that I am unable to perform a string search within the macro recorder, though.

Here's an example of what I'm trying to accomplish:

Input: [ { "prop1": 10, "prop2": 30, "last": 99 }, { "prop1": 80, "last": 10 }, { "propA": 33, "propB": 90, "propC": 38, "last": 100 } ]

Desired Output: [ { "prop1": 10, "prop2": 30, "last": 99, "new": 0 }, { "prop1": 80, "last": 10, "new": 0 }, { "propA": 33, "propB": 90, "propC": 38, "last": 100, "new": 0 } ]

I tried to accomplish this by typing the following into vim: q q /last ENTER $ a , ESC p q. I had "new: 0 copied to my clipboard. It appears that the search part isn't working because each time I run the macro, it pastes the line where the cursor started instead of on the line with the next instance of the string "last".

like image 764
Donovan McMurray Avatar asked Nov 29 '25 16:11

Donovan McMurray


1 Answers

  • You can perform this command:

    :%s#\v^(\s*)"last":\s*\d*\zs#,\r\1"new": 0#g

  • You can still achieve that using macro:

first yank this line:

 "new": 0

then perform these keystrokes:

qqq
qq/last ENTER A,ESCpq 

Note: ENTER and ESC are keys on keyboards

like image 183
Meninx - メネンックス Avatar answered Dec 02 '25 07:12

Meninx - メネンックス



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!