【问题标题】:How to get total size of folders with find and du?如何使用 find 和 du 获取文件夹的总大小?
【发布时间】:2012-04-05 09:24:02
【问题描述】:

我正在尝试使用 find 和 du 获取名为“bak”的目录的大小。

我这样做:find -name bak -type d -exec du -ch '{}' \;

但它返回每个名为“bak”的文件夹的大小而不是总数。

无论如何要得到它们?谢谢:)

【问题讨论】:

  • 我建议使用awk 来计算最终总和(使用du 而不使用-h
  • @Alex,为什么首选?

标签: bash shell debian


【解决方案1】:

如果文件很多,使用-exec ... +可能会执行multiple times,你会得到多个小计。

另一种方法是通过管道传递 find 的结果:

find . -name bak -type d -print0 | du -ch --files0-from=-

【讨论】:

  • 我认为这个答案是对原始问题最简单的解决方案。通过在管道中使用trgrep,它变得更加通用:find . -name bak | grep -v 'not this' | grep -v 'not that' | tr "\n" "\0" | du -hcs --files0-from=-
【解决方案2】:

用 find 的结果输入 du:

du -shc $(find . -name bak -type d)

【讨论】:

    【解决方案3】:

    使用xargs(1) 代替-exec

    find . -name bak -type d | xargs du -ch
    

    -exec 为找到的每个文件执行命令(查看find(1) 文档)。通过管道连接到xargs,您可以聚合这些文件名并且只运行du 一次。你也可以这样做:

    find -name bak -type d -exec du -ch '{}' \; +
    

    如果您的find 版本支持。

    【讨论】:

    • 这在 Ubuntu 12.04 上对我不起作用。将此建议的结果传递给 awk 确实有效:| awk '{ sum+=$1} END {打印总和}'
    • 为了加快速度,如果您知道要查找的目录结构,可以添加最大深度:find . -maxdepth 3 -type d -name bak | xargs du -ch --max-depth=0
    【解决方案4】:

    试试du -hcs。从手册页:

     -s, --summarize
          display only a total for each argument
    

    【讨论】:

    • 同样的问题,带 -s 或不带。
    • 嗯,你试过find -name bak -type d -exec du -ch {} +吗?
    • 试过了,好像我的find版本不支持。
    猜你喜欢
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    相关资源
    最近更新 更多