6

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

12

Using sed

Type the following command:

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

Using grep

Type the following command:

grep -v '^$' input.txt > output.txt
0
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.

4
  • 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
  • True! I understood it the other way round – fedorqui Jun 12 '15 at 21:30
  • +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 8:12
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.