1

I have a file with a list of files and directories, containing the wildcard *. I am trying to output the size of the entries with du and would like a grand total.

If I start with:

cat file | xargs du -hs

the wildcard * is not expanded. To do so, I do:

cat file | xargs -I@ sh -c 'du -hs @'

But if I try:

cat file | xargs -I@ sh -c 'du -hsc @'

I get a total for each (expanded) entry of the file. If the file looks like:

foo*
bar*

I will get:

1K foo1
1K foo2
2K total
1K bar1
1K bar2
2K total

How do I get the grand total of all entries in the file? How do I run du only once for all the lines? Thanks

2 Answers 2

0
cat file | xargs -I@ sh -c 'echo @' | xargs du -hsc
1
  • 1
    While your answer may be correct, it requires an explanation for future visitors. And perhaps a link to a reference. Commented Jul 14, 2023 at 21:50
0

If xargs isn't required, this will also produce a grand total with du:

du -hsc ${(f)~"$(<file)"}

This assumes that file has one glob pattern per line, and uses the (f) expansion flag to split the input into lines. Both the pattern and the filenames can contain spaces. The GLOB_SUBST expansion (${~...}) tells zsh to process the wildcards in the input.

If the patterns are just separated by whitespace, the (f) flag isn't needed:

setopt nullglob
du -hsc ${~$(<file)}

This sets the NULL_GLOB option. That setting will be necessary if any of the glob patterns do not have matching files.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .