Remove blank lines from a file using grep

Contributor Icon Contributed by qmchenry  
Tag Icon Tagged: UNIX  

How can I remove blank lines from a file in UNIX?


grep -v "^$" filename > newfilename

The ^$ within the quotes is a regular expression: ^=beginning of line, $=end of line, with no characters between.

See additional helpful information in the comments below.

 

15 Comments -


  1. Jadu Saikia said on January 7, 2009

    All ways together, :-)

    $ grep -v ‘^$’ file
    $ grep ‘.’ file
    $ sed ‘/^$/d’ file
    $ sed -n ‘/^$/!p’ file
    $ awk NF file
    $ awk ‘/./’ file

    unstableme.blogspot.com

  2. Luis said on March 13, 2009

    awsome

  3. Anonymous said on August 7, 2009

    Have you tried the above commans…?

  4. Anonymous said on August 19, 2009

    Include blank lines that aren’t really blank (tabs, spaces, CRLF, etc)

    grep -vc ‘^[[:space:]]*$’

  5. Anonymous said on November 19, 2009

    thanks

  6. peterpan said on March 18, 2010

    It’s cool~~~~ thanks!

  7. sonu said on May 13, 2010

    both are corrects with sed and with grep but i have same question as anonymous

  8. Mark said on June 24, 2010

    add
    | grep -v “^$”
    to the end of the command chain to eliminate blank lines.

  9. Tntnt said on October 10, 2010

    Thank you

  10. colacao said on February 22, 2011

    this is the the only one that worked for me on a file created on Windows, thanks bryansenter

  11. Anonymous said on March 24, 2011

    without the -c flag it worked for me.

  12. Guest said on March 28, 2011

    the problem with grep is it has a line limit (2048) lines. If you file has more lines than that it will stop when it gets there. I just learned a cool way to do the same thing using awk. I don’t think it has the same limitations.

    awk ‘{ if (length($0) > 0){ print $0 }}’ inputfilename >> outputfilename

    This will search inputfilename and as long as the line has one character on it it will be sent to the outputfilename eliminating blank lines in outputfilename.

  13. 2100822 said on April 28, 2011

    thank you

  14. Latthe said on August 8, 2011

    My Name is Latthe

  15. Latthe said on August 8, 2011

    RDLC is worst tool

 

RSS feed for comments on this post. TrackBack URL

Leave a comment -