Shell Command Line Text Processing Files – How to Remove Blank Lines from a File (Including Tabs and Spaces)?

command linefilesshelltext processing

I want to remove all empty lines from a file. Even if the line contains spaces or tabs it should also be removed.

Best Answer

Just grep for non-blanks:

grep '[^[:blank:]]' < file.in > file.out

[:blank:], inside character ranges ([...]), is called a POSIX character class. There are a few like [:alpha:], [:digit:]... [:blank:] matches horizontal white space (in the POSIX locale, that's space and tab, but in other locales there could be more, like all the Unicode horizontal spacing characters in UTF8 locales) while [[:space:]] matches horizontal and vertical white space characters (same as [:blank:] plus things like vertical tab, form feed...).

grep '[:blank:]'

Would return the lines that contain any of the characters, :, b, l, a, n or k. Character classes are only recognised within [...], and ^ within [...] negates the set. So [^[:blank:]] means any character but the blank ones.