简体   繁体   English

如何在vim中的每几行之后添加一行

[英]How to add a line after every few lines in vim

I wanted to add a line after every 3 lines in a file (having about 1000 lines) using vim editor. 我想使用vim编辑器在文件中每隔3行添加一行(大约1000行)。 Can someone help me out? 有人可以帮我吗?

Thanks, Alisha 谢谢,艾丽莎

there is a vim-specific regular expression to do that 有一个vim特定的正则表达式来做到这一点

  :%s/.*\n.*\n.*\n/\0\r/g
  • %s is vim ex command to substitute in the whole file %s是vim ex命令替换整个文件
  • .*\\n is a line including the end of line 。* \\ n是包含行尾的行
  • \\0 is the entire matched expression \\ 0是整个匹配的表达式
  • \\r vim way to say add a new line (not \\n as one would expect) \\ r vim的方式来说添加一个新行(不是\\ n如人们期望的那样)

Edit: if you want anything else than a new line, just put the text in front of the \\r (properly regex escaped, if it contains some regex characters) 编辑:如果你想要一个新行,只需将文本放在\\ r \\ n之前(正确的正则表达式转义,如果它包含一些正则表达式字符)

You can use a macro . 你可以使用 The complete process looks like: 完整的过程如下:

qq     " start recording to register q (you could use any register from a to z)
o      " insert an empty line below cursor
<Esc>  " switch to normal mode
jjj    " move the cursor 3 lines downward
q      " stop recording

Then just move to the start line and type 1000@q to execute your macro 1000 times. 然后只需移动到起始行并输入1000@q即可执行1000次宏。

" insert a blank line every 3 lines

:%s/\v(.*\n){3}/&\r          

: .............. command
% .............. whole file
s .............. replace
/ .............. start pattern that we will replace
\v ............. very magic mode, see :h very-magic
(.*\n) ......... everything including the line break
{3} ............ quantifier 
/ .............. start new pattern to replace
& .............. corresponds to the pattern sought in (.*\n)
\r ............. add line break

source: http://www.rayninfo.co.uk/vimtips.html 来源: http//www.rayninfo.co.uk/vimtips.html

I would do this: 我会这样做:

:%s/^/\=(line(".")%4==0?"\n":"")/g

this works if your requirement changed to " * add a new blank line every 700 line *s" :) you just change the "4" 如果您的要求更改为“* 每700行 * s 添加一个新的空白行 ”,则此功能可用 :)您只需更改“4”

PS if I need do this, I won't do it in vim. PS如果我需要这样做,我不会在vim中这样做。 sed, awk, could do it much simpler. sed,awk,可以做得更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM