Linux – Delete empty lines using sed

linuxsedunix

I am trying to delete empty lines using sed:

sed '/^$/d'

but I have no luck with it.

For example, I have these lines:

xxxxxx


yyyyyy


zzzzzz

and I want it to be like:

xxxxxx
yyyyyy
zzzzzz

What should be the code for this?

Best Answer

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.)