Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

share|improve this question
add comment

3 Answers

This sed line should do the trick:

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

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

share|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
add comment
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.

share|improve this answer
add comment

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

Like this

grep -Ev "^$" file.txt
share|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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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