Squeeze Multiple Blank Lines within vim

The Problem

I want to squeeze multiple blank lines into just one while editing in vim. I often receive source code which the author used multiple blank lines to separate functions. I don’t mind if functions or code block are one or two lines apart, but I have seen sources where functions are four or more blank lines from each other. This is annoying and I want to squeeze many of them into one.

The Solutions

The obvious solution is to use vim’s search-and-replace feature, as discussed in this post. However, my regular expression skill is very basic and I tend to forget the syntax when I need it. Hence, I devised my own solution, one which I have better luck memorizing.

My solution involes the cat command:

:%!cat -s

This short little command applies ‘cat -s’ on my entire file contents, which squeezes multiple blank lines down to one. Note that this solution will only work on Unix-like systems such as BSD, Linux, and Mac OS X. It does not work on Windows. This is one of the shortcoming of this method compare to the previous one.

Advertisements

2 thoughts on “Squeeze Multiple Blank Lines within vim

  1. Rod.ne3

    > However, my regular expression skill is very basic and I tend to forget the syntax when I need it.

    You are not alone. 🙂

  2. Ying chen

    Interesting command. but it leave 2 blank lines, not one.

    uname-a:
    Linux l.s.w.a.com 2.6.9-89.ELsmp #1 SMP Mon J un 22 12:32:43 EDT 2009 i686 i686 i386 GNU/Linux

    man cat -s –squeeze-blank never more than one single blank line.

    Created a file with contents of ” Line1, 5 blank lines, Line2 , 5 blank lines, Line3″

    ychen:labstatsion102:~/tcl>od -c m-line
    0000000 L i n e 1 \n \n \n \n \n L i n e 2 \n
    0000020 \n \n \n \n L i n e 3 \n
    0000032

    you can see there are 5 \n after each lines.

    Issue command in Vim :%!cat -s –> 11 lines filtered. why 11?

    but it still has 2 blank lines, not 1.

    ychen:labstation102:~/tcl>od -c m-line
    0000000 L i n e 1 \n \n L i n e 2 \n \n L i
    0000020 n e 3 \n
    0000024

    I aslo tried:

    cat -s m-line> m-line-2> same result. 2 blank lines, not one.
    Anything that I missed.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s