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." />

Remove blank lines from a file using grep

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.

 

About Quinn McHenry

Quinn was one of the original co-founders of Tech-Recipes. He is currently crafting iOS applications as a senior developer at Small Planet Digital in Brooklyn, New York.
View more articles by Quinn McHenry

The Conversation

Follow the reactions below and share your own thoughts.

  • http://unstableme.blogspot.com Jadu Saikia

    All ways together, :-)

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

    unstableme.blogspot.com

  • Luis

    awsome

  • Anonymous

    Have you tried the above commans…?

  • Anonymous

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

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

    • colacao

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

    • Anonymous

      without the -c flag it worked for me.

  • Anonymous

    thanks

  • peterpan

    It’s cool~~~~ thanks!

  • sonu

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

  • Mark

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

  • Tntnt

    Thank you

  • Guest

    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.

  • 2100822

    thank you

  • Latthe

    My Name is Latthe

    • Latthe

      RDLC is worst tool

  • Alexcy

    Thanks very much! I like the grep ‘.’ file for it’s simplicity :)