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
:g
initiates a global search.^
marks the beginning of a line\s*
matches any whitespace (spaces or tabs), including zero occurrences., i.e., blank lines.$
marks the end of a lined
deletes the lines matching^\s*$
.
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
:g
initiates a global search.^$
matches lines with nothing between the start (^
) and end ($
) of a line, i.e., blank lines.d
deletes the matched lines.
Further readings #
Sources and recommended, further resources on the topic:
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.