Linux / Unix: Shell Remove Empty Lines

by on April 24, 2013 · 3 comments· LAST UPDATED April 24, 2013

in , , , ,

I am a new Linux user. I have text files with lots of empty lines. How do I delete all empty lines under Linux or Unix operating systems?

You can use any one of the following utility to delete all empty lines from text file:

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
Estimated completion timeN/A
[a] sed command

[b] awk command

[c] perl command


The syntax is:

command input.txt > output.txt
command [option] input.txt > output.txt
sed '...' input.txt > output.txt
## Gnu/sed
sed -i '...' input.txt
awk '...' input.txt > output.txt

sed command examples

Type the following sed command to delete all empty files:

sed '/^$/d' input.txt > output.txt
cat output.txt


sed -i '/^$/d' input.txt
cat input.txt

awk command examples

Type the following awk command to delete all empty files:

awk 'NF > 0' input.txt > output.txt
cat output.txt

perl command examples

Type the following perl one liner to delete all empty files and save orignal file as input.txt.backup:

perl -i.backup -n -e "print if /\S/" input.txt

Verify updated files, type:

cat input.txt
cat input.txt.backup
Tweet itFacebook itG+ itDownload PDF versionFound an error/typo on this page?

{ 3 comments… read them below or add one }

1 Roy April 25, 2013 at 12:24 am

You can also use grep :)

cat output.txt | grep -v “^$” | less


2 Constantine Shulyupin April 25, 2013 at 8:14 am
cat --squeeze-blank

suppress repeated empty output lines


3 MisaT April 25, 2013 at 10:59 am

I am using grep also, but like this:

grep . input.txt > output.txt

There is a dot between grep and input.txt.


Leave a Comment

Tagged as: , ,

Previous Faq:

Next Faq: