Why does "find . -name *.txt | xargs du -hc" give multiple totals?

Alex picture Alex · Aug 24, 2009 · Viewed 9.7k times · Source

I have a large set of directories for which I'm trying to calculate the sum total size of several hundred .txt files. I tried this, which mostly works:

find . -name *.txt | xargs du -hc

But instead of giving me one total at the end, I get several. My guess is that the pipe will only pass on so many lines of find's output at a time, and du just operates on each batch as it comes. Is there a way around this?

Thanks! Alex

Answer

Sbodd picture Sbodd · Aug 24, 2009

How about using the --files0-from option to du? You'd have to generate the null-terminated file output appropriately:

find . -name "*txt" -exec echo -n -e {}"\0" \; | du -hc --files0-from=-

works correctly on my system.