Need a quick way to add up file sizes in Linux

Say I have a bunch of files in a Linux directory called foo.1, foo.2, and so forth, and I want to know the total size of all the files. If they were the only files in the directory, I could use “du -ab --max-depth=1” and then ignore everything but the last line. But they’re not the only files in the directory, and the other files don’t match any fixed pattern that I could use with the “-exclude” option to du.

Currently, I’m using the following hideous bit of hackery:


ls -l foo.* | awk '{print $5}' | perl -ple '$_=$t+=$_' | tail -n 1

But there’s got to be a better way than that. Anyone know what it is?

(There’s probably some perfectly obvious Unix command that does this that I just don’t know about…)

Awk can do the math for you.


ls -l foo.* | awk '{print sum+=$5}' | tail -n 1

See? I knew there was some bit of Unix arcana I didn’t know that would help. Thanks!

(In case it’s not blindingly obvious, someone once showed me how awk could be used to extract a given column from text output and I haven’t used it for anything else since.)

How about doing it with only one pipe?


ls -l foo.* | awk '{tot+=$5} END {print tot}'

gotcha all beat

cat foo.* | wc -c

Ok, that’s not a great idea if your files have any size to them.

du -c foo.*

will give you a total at the end, but will also show you the size of all the files that match the expression. You could do

du -c foo.* | tail -1

if you only want the total line. And of course it will say “total” after the total size, so you’d have to strip that off if you cared.

I’d do it all in Perl, myself:



perl -e 'for (glob "foo.*") {$sum += -s} print "$sum
";'


I think that’s clearer than most of the shell alternatives, and it can be trivially migrated to its own file for use as a standalone program.

(Yes, that’s tested code. I love Linux. :D)