Reputation: 1385
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
Upvotes: 29
Views: 29217
Reputation: 11800
" 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
Upvotes: 10
Reputation: 149796
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.
Upvotes: 25
Reputation: 195059
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"
P.S. if I need do this, I won't do it in vim. sed, awk, could do it much simpler.
Upvotes: 6
Reputation: 3078
there is a vim-specific regular expression to do that
:%s/.*\n.*\n.*\n/\0\r/g
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)
Upvotes: 45