Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

contents of file.txt


output desired

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 '15 at 16:11

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
It actually needs to be "/^ *$/d" to remove lines that only contain spaces. – Sean Reifschneider Mar 28 '11 at 23:36
@SeanReifschneider That requirement was not in the question when this answer was written? – kasperd Apr 18 at 10:02
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

Note: The :bufdo command is not POSIX.

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
note bufdo is not POSIX – Steven Penny Apr 17 at 0:39

Your Answer


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.