Skip to main content

How to delete all blank lines in Vim

Summary

This guide explains how to use Vim commands to delete all blank lines or lines containing only whitespace for efficient text cleanup. Also applies to Neovim.

Introduction #

Efficiently managing blank or whitespace-filled lines is a common task when editing text files. This short guide provides two simple Vim commands to delete all blank lines or selectively remove only those with or without whitespace (spaces or tabs). Happy Hacking.

Delete All Blank Lines and Lines with Whitespace #

The following command deletes all blank lines, including those with whitespace.

In Vim normal mode (press Esc if you are not in normal mode), enter the following command:

:g/^\s*$/d

Delete All Blank Lines Only #

The following command only deletes blank lines, excluding those with whitespace (space characters).

In Vim normal mode (press Esc if you are not in normal mode), enter the following command:

:g/^$/d

Further readings #

Sources and recommended, further resources on the topic:

Author

Jonas Jared Jacek • J15k

Jonas Jared Jacek (J15k)

Jonas works as project manager, web designer, and web developer since 2001. On top of that, he is a Linux system administrator with a broad interest in things related to programming, architecture, and design. See: https://www.j15k.com/

License

License: How to delete all blank lines in Vim by Jonas Jared Jacek is licensed under CC BY-SA 4.0.

This license requires that reusers give credit to the creator. It allows reusers to distribute, remix, adapt, and build upon the material in any medium or format, for noncommercial purposes only. To give credit, provide a link back to the original source, the author, and the license e.g. like this:

<p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://www.ditig.com/instructions/how-to-delete-all-blank-lines-in-vim">How to delete all blank lines in Vim</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://www.j15k.com/">Jonas Jared Jacek</a> is licensed under <a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank" rel="license noopener noreferrer">CC BY-SA 4.0</a>.</p>

For more information see the DITig legal page.


“Less is more.”

Ludwig Mies van der Rohe, German architect and designerWord of mouth, - IT quotes