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
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
grep with the following syntax. GNU versions of
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.