I am measuring the total sizes of a bunch of files, whose paths I have stored in a text document, files.txt. Example contents of files.txt:


This shell command gives me the output I want:

$ du -hc $(cat files.txt)

unless I have a filename with spaces in it, e.g.: file 9.txt Then, du -hc tries to parse the file name at the space. No matter where I seem to put quotations, in files.txt or in my shell command, it still parses incorrectly. What should I do instead?

FYI, my file list document is output of a command like so:

find ~/Dropbox/ -type f -iname "*.BMP" >> bmpfound.txt

My system details: MacOS, using oh-my-zsh in Terminal.app

  • If you have xargs, try cat files.txt|xargs -I{} du -hc "{}", but this will probably fail with file names with ". More safe maybe is to do it in a loop while read line;do du -hc "$line";done <files.txt
    – Paulo
    Feb 18 '18 at 13:17
  • 2
    If your du takes arg --files0-from then use that and change your find to add -print0.
    – meuh
    Feb 18 '18 at 14:01

Leverage the -print0 option in find and pipe to xargs -0:

find ~/Dropbox/ -type f -iname "*.BMP" -print0 | xargs -0 du -ch

Alternatively, as Gordon Davisson commented, this can be simplified:

find ~/Dropbox/ -type f -iname "*.BMP" -exec du -ch {} +

Either of these should work with filenames that contain spaces, or any manner of goofy characters, for that matter.

I'm not sure if you meant to intentionally redirect find's output to a file rather than piping it, but if you actually desired to keep the file list around, you could do this instead:

xargs -0 du -ch < bmpfound.txt
  • 1
    If you don't need to store the find results in a file, you can make it even simpler with find ~/Dropbox/ -type f -iname "*.BMP" -exec du -ch {} + Mar 25 '18 at 7:07
  • @GordonDavisson Brilliant! I had initially tried the -exec du route, but somehow completely missed the + syntax. That's very handy.
    – ZeroKnight
    Mar 25 '18 at 7:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.