Delete lines that contain only spaces

Viewed 88

Consider following file.

Dalot
# Really empty line
Eriksen
   # Line containing space
Malacia
        # Line containing tab
# Really empty line
Varane

How do I remove line that ONLY contain either whitespace or tab on it, and leaving empty line intact. The other answer here mostly will remove all empty line including spaces and tab.

Following is desired output.

Dalot
# Really empty line
Eriksen
Malacia 
# Really empty line
Varane
5 Answers
sed -E '/^[\t ]+$/d'

i.e. "If the line contains spaces and tabs only, remove it".

This might work for you (GNU sed):

sed '/\S/!d' file

Delete all lines that do not contain at least one non-white spaced character.

Alternative:

sed '/^\s*$/d' file
$ awk '/^(|[^\t ]+)$/' file

or

$ sed -En '/^(|[^\t ]+)$/p' file

print if no chars or at least one non-whitespace char.

Note that @choroba did the reverse of this logic to delete lines, which is actually smarter.

cat file | tr ' ' | tr '\t' > f2
mv f2 file
Related