How do I remove empty/blank (including spaces only) lines in a file in Unix/Linux using the command line ?

contents of file.txt

Line:Text
1:<blank>
2:AAA
3:<blank>
4:BBB
5:<blank>
6:<space><space><space>CCC
7:<space><space>
8:DDD

output desired

1:AAA
2:BBB
3:<space><space><space>CCC
4:DDD

Thanks Michael

link|improve this question

feedback

3 Answers

This sed line should do the trick:

sed -i '/^$/d' file.txt

The -i means it will edit the file in-place.

link|improve this answer
1  
It actually needs to be "/^ *$/d" to remove lines that only contain spaces. – Sean Reifschneider Mar 28 '11 at 23:36
feedback
sed '/^$/d' file.txt

d is the sed command to delete a line. ^$ is a regular expression matching only a blank line, a line start followed by a line end.

link|improve this answer
feedback

You can use the -v option with grep to remove the matching empty lines.

Like this

grep -Ev "^$" file.txt
link|improve this answer
I don't believe you need the -E, at least not with GNU grep, but apart from that I'm so pleased to see this done with grep! It's what I reach for in preference to sed, every time; in-line filters seem to me to be better than in-line editors. – MadHatter Mar 28 '11 at 22:45
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.