简体   繁体   中英

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. Can someone help me out?

Thanks, Alisha

there is a vim-specific regular expression to do that

  :%s/.*\n.*\n.*\n/\0\r/g
  • %s is vim ex command to substitute in the whole file
  • .*\\n is a line including the end of line
  • \\0 is the entire matched expression
  • \\r vim way to say add a new line (not \\n as one would expect)

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)

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.

" 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

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"

PS if I need do this, I won't do it in vim. sed, awk, could do it much simpler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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