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.
1 |
$ sed '/^$/d' input.txt > output.txt |
1 |
$ 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.
1 |
$ sed '/^[[:blank:]]*$/d' input.txt > output.txt |
1 |
$ grep -v '^[[:blank:]]*$' input.txt > output.txt |
Another neat trick is to use awk
and remove the blank lines.
1 |
$ awk NF input.txt > output.txt |
If you are not sure which syntax to use, choose one from the blank lines section.