I was busy with my work today when all of a sudden my colleague interrupted me to enquire how to delete empty lines in a file in Linux. I answered his requirement and thought of creating this post hoping that it would be helpful to others who may be in need of similar requirement.
There are multiple ways to delete empty lines in a file in Linux. Today, we will consider using ‘
sed’ for this purpose.
SED is an acronym for Stream Editor. It’s a Swiss army knife for performing basic text transformations on a stream of input. The below command would delete all empty lines from the input.
sed ‘/^$/d’ <input-file-name>
sed ‘/^$/d’ file_with_empty_lines.txt
The output of the ‘
sed’ command is by default dumped on the output console. If you expect ‘
sed’ to overwrite the contents of the file with transformed output, then the in-place edit option of ‘
sed’ comes to rescue.
sed –i ‘/^$/d’ file_with_empty_lines.txt
In-case you prefer to backup the original file before replacing its contents with the transformed output of ‘
sed’, specify a file extension following the ‘
sed –ibak ‘/^$/d’ file_with_empty_lines.txt
In general, to delete all the occurrences of a specific work from a file or an input stream, use ‘
sed’ as below.
sed –i ‘/Linux/d’ file.txt
- UNIX man pages : sed- http://unixhelp.ed.ac.uk/CGI/man-cgi?sed
- Sed – An Introduction and Tutorial – http://www.grymoire.com/Unix/Sed.html
- sed – http://www.opengroup.org/onlinepubs/007908799/xcu/sed.html
- man sed (1posix) – stream editor – http://pwet.fr/man/linux/commandes/posix/sed