bspckl
bspckl

Reputation: 197

Vim regex to add curly braces every few lines

I am creating a json file and have worked out how to append double quotes and such to appropriate lines, but I need to know how to wrap every 2 lines in curly braces.

Ex:

"value": "Bahraini Foreign Ministry"
"tag": "project:bahrain;id:2201",
"value": "Bahraini Foreign Minister"
"tag": "project:bahrain;id:2202",

needs to be:

{
"value": "Bahraini Foreign Ministry"
"tag": "project:bahrain;id:2201",
},
{
"value": "Bahraini Foreign Minister"
"tag": "project:bahrain;id:2202",
},

I have tried with :%norm and :%s and am going around in circles here. Any ideas are appreciated!

Upvotes: 1

Views: 285

Answers (1)

DJMcMayhem
DJMcMayhem

Reputation: 7679

dNitro's solution is one way to do it. Here is another way:

qqqqqqO{<esc>jjo},<esc>j@qq@q

This creates a recursive macro, e.g. a macro that calls itself. Since recursive macros run until they hit an error, and calling j on the last line throws an error, this will work for any data size. Explanation:

qqq clear the register 'q'. qq starts recording in register 'q'. O{<esc> inserts a bracket on the line above the current line. jj moves down (to the line with "tag" on it). o},<esc> puts a bracket on the next line after the current one. j@q puts on back on a line with "value", and @q calls the 'q' macro. Since it's empty while you record, this won't actually do anything. However, once you hit q@q, this will stop recording, and then call this recursive macro.

Another alternative is to use the :global command, e.g.

:g/value/normal O{^[jjo},

Note that ^[ is a literal escape character that you must enter by pressing "ctrl-v, ctrl-esc"

This is essentially the same thing, except instead of using a macro, it automatically applies the set of keystrokes after "normal" to every line containing the text "value".

And just for fun, here is one last alternative, a substitute command:

:%s/.*"value".*\n.*,/{\r&\r},,

This replaces two lines where the first line contains the text "value", with the same text enclosed in brackets.

Upvotes: 2

Related Questions