【问题标题】:Calculate the total size of all files from a generated folders list with full PATH使用完整路径计算生成的文件夹列表中所有文件的总大小
【发布时间】:2021-04-06 17:43:14
【问题描述】:

我有一个包含多个具有完整路径的目录的列表:

/mnt/directory_1/sub_directory_1/

/mnt/directory_2/

/mnt/directory_3/sub_directory_3/other_directories_3/

我需要计算这个列表的总大小。

来自Get total size of a list of files in UNIX

du -ch $file_list | tail -1 | cut -f 1

这是我能找到的最接近的答案,但给了我以下错误消息:

bash: /bin/du: 参数列表太长

【问题讨论】:

  • I have a list containing 列表是如何存储的? $file_list - 变量$file_list的内容是什么?
  • 遍历列表并对结果求和。
  • @KamilCuk 和 William 说的:另外:如果有多种单位(例如一些 K/M/G in输出)。
  • @KamilCuk $file_list 是文件名。我这样运行它: du -ch 'cat file_list.txt` |尾-1 | cut -f 1 内容就是上面提到的完整路径。这些目录和子目录中的每一个都包含具有不同扩展名的文件。我在 pastebin 上有一个结构示例(小规模):pastebin.com/xEAj9csy 在这个示例中它可以工作,但是当您有太多文件(100k)时,我收到错误:bash: /bin/du: Argument list too long There is使用此方法时存在限制,我正在寻找解决方法。

标签: linux ls du


【解决方案1】:

不要使用反引号`。请改用$(..)

不要使用:

command $(cat something)

这是一种常见的模式。它适用于简单的情况,失败的情况更多,因为$(...) 的结果经历了分词和文件名扩展。

使用http://shellcheck.net检查您的脚本

如果您想“使用文件中的参数运行命令”,请使用xargs 或编写一个循环。阅读https://mywiki.wooledge.org/BashFAQ/001xargs 也会自己处理太多的参数。我还将-s 添加到du。试试:

xargs -d'\n' du -sch < file_list.txt | tail -1 | cut -f 1

repl bash上测试

【讨论】:

  • 嗨@KamilCuk,这可能是一个愚蠢的跟进,但你的解决方案给了我另一个错误:du:无法访问'./mnt/directory_1\r':没有这样的文件或目录它添加和\ r 到每个目录的末尾。从站点linuxhint.com/bash_xargs_command_by_example 我尝试了以下操作,但结果相同: xargs -i -d '\n' du -sch {}
  • 您的文件有 dos 行结尾。删除它们。
  • error: xargs: error closing file - 您在xargs 运行时编辑或删除了文件du: invalid zero-length file name 您的输入文件有空行。删除它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-21
  • 2015-06-15
  • 2011-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
相关资源
最近更新 更多