[vim] Vim delete blank lines

What command can I run to remove blank lines in Vim?

This question is related to vim vi

The answer is


Press delete key in insert mode to remove blank lines.


I tried a few of the answers on this page, but a lot of them didn't work for me. Maybe because I'm using Vim on Windows 7 (don't mock, just have pity on me :p)?

Here's the easiest one that I found that works on Vim in Windows 7:

:v/\S/d

Here's a longer answer on the Vim Wikia: http://vim.wikia.com/wiki/Remove_unwanted_empty_lines


This function only remove two or more blank lines, put the lines below in your vimrc, then use \d to call function

fun! DelBlank()
   let _s=@/
   let l = line(".")
   let c = col(".")
   :g/^\n\{2,}/d
   let @/=_s
   call cursor(l, c)
endfun
map <special> <leader>d :keepjumps call DelBlank()<cr>

:v/./d

or

:g/^$/d

or

:%!cat -s

work with perl in vim:

:%!perl -pi -e s/^\s*$//g


Found it, it's:

g/^\s*$/d

Source: Power of g at vim wikia

Brief explanation of :g

:[range]g/pattern/cmd

This acts on the specified [range] (default whole file), by executing the Ex command cmd for each line matching pattern (an Ex command is one starting with a colon such as :d for delete). Before executing cmd, "." is set to the current line.


If something has double linespaced your text then this command will remove the double spacing and merge pre-existing repeating blank lines into a single blank line. It uses a temporary delimiter of ^^^ at the start of a line so if this clashes with your content choose something else. Lines containing only whitespace are treated as blank.

%s/^\s*\n\n\+/^^^\r/g | g/^\s*$/d | %s/^^^^.*

This works for me

:%s/^\s*$\n//gc


This worked for me:

:%s/^[^a-zA-Z0-9]$\n//ig

It basically deletes all the lines that don't have a number or letter. Since all the items in my list had letters, it deleted all the blank lines.


The following can be used to remove only multi blank lines (reduce them to a single blank line) and leaving single blank lines intact:

:g/^\_$\n\_^$/d

:g/^\s*$/d
^ begin of a line
\s* at least 0 spaces and as many as possible (greedy)
$ end of a line

paste

:command -range=% DBL :<line1>,<line2>g/^\s*$/d

in your .vimrc,then restart your vim. if you use command :5,12DBL it will delete all blank lines between 5th row and 12th row. I think my answer is the best answer!


How about:

:g/^[ \t]*$/d

  1. how to remove all the blanks lines

    :%s,\n\n,^M,g
    

    (do this multiple times util all the empty lines went gone)

  2. how to remove all the blanks lines leaving SINGLE empty line

    :%s,\n\n\n,^M^M,g
    

    (do this multiple times)

  3. how to remove all the blanks lines leaving TWO empty lines AT MAXIMUM,

    :%s,\n\n\n\n,^M^M^M,g
    

    (do this multiple times)

in order to input ^M, I have to control-Q and control-M in windows