sed -i.bak '/^[[:space:]]*$/d' file_name

Remove blank lines from a file

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

0
2009-04-07 11:32:06
sed

These Might Interest You

What Others Think

"sed -i '/^\ *$/d' file_name" does the same
prayer · 476 weeks and 2 days ago
Following will remove spaces and comments sed '/ *#/d; /^ *$/d' file_name
alperyilmaz · 476 weeks and 2 days ago
sed -i '/^\s*$/d' file_name eliminates blank lines or lines with whitespace (spaces, tabs, etc.)
daithif · 476 weeks and 2 days 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 · 476 weeks and 2 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?

commandlinefu.com 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.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

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: