Linux: Remove Blank / Empty Lines from File

Objective: Remove all blank and empty lines from a text file on Linux.

Let’s clear up a few things before we start. Blank lines could refer to a line with the line feed as the one and only character. Or, it could also mean that the line contain spaces and tabs.

In this article, we will define empty line and blank line differently.

Empty line will mean that the line only has the line feed character and the “^$” regular expression will be able to match that line.

Blank line will mean that the line will have spaces and tabs and terminated with a line feed character.

To remove empty lines from a file, use sed or grep with the following syntax.

$ sed '/^$/d' input.txt > output.txt
$ grep -v '^$' input.txt > output.txt

To remove blank lines from a file, use sed or grep with the following syntax. GNU versions of sed and grep are necessary.

$ sed '/^[[:blank:]]*$/d' input.txt > output.txt
$ grep -v '^[[:blank:]]*$' input.txt > output.txt

Another neat trick is to use awk and remove the blank lines.

$ awk NF input.txt > output.txt

If you are not sure which syntax to use, choose one from the blank lines section.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react, vuejs); plays_on(xbox, ps4); linux_desktop_user(true); }

« Previous Article