Remove blank lines from a file

sed -i.bak '/^[[:space:]]*$/d' file_name
Remove blank lines from files, even if some of the lines have whitespace (spaces, tabs, etc.). Also creates a .bak copy of the original file. Works on Mac also. Thanks to those all those who left comments.
Sample Output
$ cat aFile
This is an example file
^ with a blank line
$ sed -i.bak '/^[[:space:]]*$/d' aFile
$ cat aFile
This is an example file
^ with a blank line
$ cat aFile.bak
This is an example file
^ with a blank line

2009-04-07 11:32:06

What Others Think

"sed -i '/^\ *$/d' file_name" does the same
prayer · 650 weeks and 1 day ago
Following will remove spaces and comments sed '/ *#/d; /^ *$/d' file_name
alperyilmaz · 650 weeks and 1 day ago
sed -i '/^\s*$/d' file_name eliminates blank lines or lines with whitespace (spaces, tabs, etc.)
daithif · 650 weeks and 1 day ago
@daithif: Great job! However, your command only works on Linux (Ubuntu 8.10), but not on Mac OS X (I tested against Leopard 10.5.6). The following works on both: sed -i.bak '/^[[:space:]]*$/d' file_name It also makes a back up with the .bak extension.
haivu · 650 weeks ago
Here in this article it shares the lines of code for removing blank lines from a file. It also provides check this out the sample output here that helps everyone to understand what they are trying to share through these commands. I am looking here for more details on that.
Alyssalauren · 14 weeks and 6 days ago
Hi there, I found your blog via Google while searching for such kinda informative post and your post looks very interesting for me.">paphos holidays
ayesha · 3 weeks and 1 day ago
Welcome to Pro Pharmacy Store. We are one of the most trusted online pharmacies and one of the largest visited site in the UK. Having an industry experience of more than a decade with wide variety of pharmaceutical products available for sale. buy pregabalin 150mg online
KayGasaway · 2 weeks and 6 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this? is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.


Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: