Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

What is the easiest way to remove blank lines from multiple files at once?

I'm working on Solaris 10.

share|improve this question
add comment

3 Answers

up vote 4 down vote accepted

A quick little script should work. I got this from nixCraft a while a go and it works quite well.

#!/bin/sh
files="/home/me/data/*.txt"
for i in $files
do
  sed '/^$/d' $i > $i.out
  mv  $i.out $i
done

Replace $files for your needs.

share|improve this answer
add comment

It'll be easiest to remove all blank lines:

sed -i.bak '/^$/d' $FILES

This will create a backup with the extension .bak, take that out if you don't want a backup.

If you want to remove lines with whitespace (and only whitespace) too, add \W*:

sed -i.bak '/^\W*$/d' $FILES

And this works with the --posix option in gnu sed (turns off gnu extensions, so I think this should work on solaris):

sed -i.bak '/^[ \t]*$/d' $FILES

Add more whitespace characters if necessary.

share|improve this answer
    
That would've been perfect if I had GNU sed available. I should've mention that. I'm editing my question. –  rahmu Dec 13 '11 at 16:35
    
I've added a line; if that one doesn't work, then which part doesn't work/behave the same? –  Kevin Dec 13 '11 at 16:42
    
The -i option is unfortunately not available. I just got home and tried it, and it worked as expected on Debian. –  rahmu Dec 13 '11 at 18:44
add comment

You can use the following single line command to remove blank lines across multiple files

find directoryname -name "filename" -print | xargs sed -i '/^$/d'

If for example you want to remove the blank lines from all the files found within the current directory and its sub-directories, you can use the following command:

find . -name "*.*" -print | xargs sed -i '/^$/d'
share|improve this answer
add comment

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.