8

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

Maythux
  • 84,289
wb9688
  • 1,437

5 Answers5

13

Using sed

Type the following command:

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

Using grep

Type the following command:

grep -v '^$' input.txt > output.txt
Maythux
  • 84,289
8

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.

terdon
  • 100,812
  • for the sake of completeness, you can also say grep -v '.' file. – fedorqui Jun 12 '15 at 19:04
  • 1
    @fedorqui indeed, but I think you meant grep '.' file, we want to remove empty lines, not keep them. – terdon Jun 12 '15 at 19:26
  • +1, however the -r switch on the sed command is not really needed there since you're not taking advantage of ERE-specific syntax – kos Jun 13 '15 at 08:12
1

Sometimes the other commands will fail to remove blank lines if the lines contain a blank space. The following will remove all blank lines including lines that contain only blank spaces.

grep -v '^[[:space:]]*$' input.txt > output.txt
mchid
  • 43,546
  • 8
  • 97
  • 150
  • Is a nice solutions, in xml files for example is possible to have spaces. A similar solution with sed can be: "sed '/^\s*$/d' input.txt > output.txt" – TheGabiRod Nov 16 '22 at 19:58
0

You can do this in the default Ubuntu Text Editor (gedit) by:

  • Press Ctrl+H to open Find and Replace
  • In the 'Find' box, enter \n\n which signifies two new lines without text in-between them.
  • In the 'Replace' box, enter \n
  • Click 'Replace All'

If the text file was produced in windows, you may want to try \r\n.

Jaydin
  • 1,446
0

You can use Vim in Ex mode:

ex -sc v/./d -cx hosts
  1. /./ find non blank lines

  2. v invert selection

  3. d delete

  4. x save and close

Zombo
  • 1