[英]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. 我正在创建一个json文件,并且已经弄清楚了如何在适当的行上添加双引号等,但是我需要知道如何将每2行用大括号括起来。
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. 我已经尝试过:%norm
和:%s
并且在这里转了一圈。 Any ideas are appreciated! 任何想法表示赞赏!
dNitro's solution is one way to do it. dNitro的解决方案是做到这一点的一种方法。 Here is another way: 这是另一种方式:
qqqqqqO{<esc>jjo},<esc>j@qq@q
This creates a recursive macro, eg 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. 由于递归宏会一直运行直到遇到错误,并且在最后一行调用j
会引发错误,因此这适用于任何数据大小。 Explanation: 说明:
qqq
clear the register 'q'. qqq
清除寄存器“ q”。 qq
starts recording in register 'q'. qq
开始记录在寄存器“ q”中。 O{<esc>
inserts a bracket on the line above the current line. O{<esc>
在当前行上方的行上插入一个括号。 jj
moves down (to the line with "tag" on it). jj
向下移动(移至带有“ tag”的行)。 o},<esc>
puts a bracket on the next line after the current one. o},<esc>
在当前行之后的下一行放置一个括号。 j@q
puts on back on a line with "value", and @q
calls the 'q' macro. j@q
穿回用“价值”的线路,并@q
调用“Q”宏。 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. 但是,一旦按下q@q
,它将停止记录,然后调用此递归宏。
Another alternative is to use the :global
command, eg 另一种选择是使用:global
命令,例如
:g/value/normal O{^[jjo},
Note that ^[
is a literal escape character that you must enter by pressing "ctrl-v, ctrl-esc" 请注意, ^[
是字面转义字符,您必须通过按“ 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. 这将替换第一行包含文本"value"
两行,并在方括号中包含相同的文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.