How do I remove blank lines from files?

I have a file (hosts) with some lines without content, how do I remove that lines without content?


Using sed

Type the following command:

sed '/^$/d' input.txt > output.txt

Using grep

Type the following command:

grep -v '^$' input.txt > output.txt

Many ways:

  1. Use sed and edit the file in place.

    sudo sed -i -rn '/\S/p' /etc/hosts
    
  2. Same, but with Perl:

    sudo perl -i -ne 'print if /\S/' /etc/hosts
    
  3. Newer versions of GNU awk, in place again:

    sudo awk -i inplace '/\S/' file
    

All of the above solutions will also remove lines that contain nothing but whitespace. If you only want to remove empty lines, and leave lines that contain spaces or tabs etc, change the /\S/ to /^$/ in all of the above examples.