Calculating file size in bash

When we face the problem of calculating size of some files then we often think of du.. But how could we count size of files found by find? We could do this with this simple one-liner:

find /somewhere -name 'some_files*' -exec wc -c '{}' +

Find command is simple here. We use here also a POSIX solution – ending “exec” with a plus-sign not a semicolon. This form groups the finding results into sets and then run commands on whole that set. And that’s why we use it here – our wc -c command is run on a whole set of results giving us in the end line the total size of all the files:

[email protected] log]# find . -name 'maillog*' -exec wc -c '{}' +<br />
 6847 ./maillog-20111120<br />
 6137 ./maillog<br />
 6580 ./maillog-20111204<br />
 5028 ./maillog-20111113<br />
 6424 ./maillog-20111127<br />
31016 total

We could shorten that a little:

[email protected] log]# find . -name 'maillog*' -exec wc -c '{}' + | tail -1<br />
31016 total

And If we would like to have only the number:

[email protected] log]# find . -name 'maillog*' -exec wc -c '{}' + | tail -1 | cut -d' ' -f 1<br />