Take the 2-minute tour ×
Server Fault is a question and answer site for 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
share|improve this question
    
For awk, see: Remove blank lines in awk, or using grep, in general, see: How to remove blank lines from a file in shell? –  kenorb May 5 at 16:11

4 Answers 4

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
2  
It actually needs to be "/^ *$/d" to remove lines that only contain spaces. –  Sean Reifschneider Mar 28 '11 at 23:36
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

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

Simply using grep:

grep . file

Or try ex-way:

ex -s +'v/\S/d' -cwq test.txt

For multiple files (edit in-place):

ex -s +'bufdo!v/\S/d' -cxa *.txt

Without modifying the file (just print on the standard output):

cat test.txt | ex -s +'v/\S/d' +%p +q! /dev/stdin
share|improve this answer

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.