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.

I'm working on Solaris 10.What is the easiest way to remove blank lines from multiple files at once?

share|improve this question

4 Answers 4

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

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

Different ways to only remove trailing empty lines:

printf %s\\n "$(cat file)"|sponge file
tac file|awk /./,0|tac|sponge file
perl -0777 -pi -e 's/\n*$/\n/' file
gsed -i ':1;/^\n*$/{$d;N;b1}' file
bsdsed -i '' -e :1 -e '/^\n*$/{$d;N;b1' -e '}' file

Command substitutions remove all trailing linefeeds, so for example echo "$(printf 'a\n\n')b" prints ab.

sponge is from moreutils.

Replace tac with tail -r in BSD.

perl -0777 sets $_ to the whole input and -p prints $_ after each line. See man perlrun.

: sets a label, b branches to a label, $d deletes the pattern space on the last line, and N appends the next line to the pattern space.

GNU sed allows semicolons after : and b but POSIX and BSD sed don't. -i works with GNU sed but not BSD sed and -i '' works with BSD sed but not GNU sed.

share|improve this answer

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

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.