Reputation: 199
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".
Upvotes: 3
Views: 2530
Reputation: 6421
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
Upvotes: 2