Remove blank lines from a file using grep

Contributor Icon Contributed by qmchenry Date Icon September 15, 2003  
Tag Icon Tagged: UNIX


grep -v "^$" filename > newfilename

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

Previous recipe | Next recipe |
 
  • Anonymous
    From man grep:

    <ul id="quote">The caret ^ and the dollar sign $ are metacharacters that respectively
    match the empty string at the beginning and end of a line.</ul>
    Not "$=beginning of line, ^=end of line"
  • qmchenry
    Great catch! You are absolutely correct. The recipe has been repaired. Thank you for helping to improve Tech-Recipes.

    Quinn
  • raxxal
    By the way, if you want to see the $ sign, in vi enter :set list
    also, in cat do the following: cat -vet

    Raxxal
  • Anonymous
    .. or, quicker, grep . <filename>
  • Luis
    awsome
  • Anonymous
    This wasn't working for me using Cygwin, then I realised that the file I was looking at had Windows line endings. There are any number of solutions to this, but the one I chose was to pipe through tr -d "r" before piping through grep. Then it worked like a charm. -- Richie Hindle, richie@entrian.com
  • Anonymous
    The easiest way to remove blank lines from a file is to use a sed statement. The following syntax removes the blank lines.

    # cat my_file | sed /^$/d
  • All ways together, :-)

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

    unstableme.blogspot.com
  • sivapitchai
    Have you tried the above commans...?
  • bryansenter
    Include blank lines that aren't really blank (tabs, spaces, CRLF, etc)

    grep -vc '^[[:space:]]*$'
  • sg1973
    thanks
blog comments powered by Disqus