Delete empty lines using sed

You may have spaces or tabs in your "empty" line. Use POSIX classes with sed to remove all lines containing only whitespace:

sed '/^[[:space:]]*$/d'

A shorter version that uses ERE, for example with gnu sed:

sed -r '/^\s*$/d'

(Note that sed does NOT support PCRE.)


I am missing the awk solution:

awk 'NF' file

Which would return:

xxxxxx
yyyyyy
zzzzzz

How does this work? Since NF stands for "number of fields", those lines being empty have 0 fields, so that awk evaluates 0 to False and no line is printed; however, if there is at least one field, the evaluation is True and makes awk perform its default action: print the current line.


sed

  • '/^[[:space:]]*$/d'
  • '/^\s*$/d'
  • '/^$/d'
  • -n '/^\s*$/!p'

grep

  • .
  • -v '^$'
  • -v '^\s*$'
  • -v '^[[:space:]]*$'

awk

  • /./
  • 'NF'
  • 'length'
  • '/^[ \t]*$/ {next;} {print}'
  • '!/^[ \t]*$/'

sed '/^$/d' should be fine, are you expecting to modify the file in place? If so you should use the -i flag.

Maybe those lines are not empty, so if that's the case, look at this question Remove empty lines from txtfiles, remove spaces from start and end of line I believe that's what you're trying to achieve.

Tags:

Linux

Unix

Sed