我正在尝试获得满足 a 的文件总大小find,例如:
ls $(find -maxdepth 2 -type f)
Run Code Online (Sandbox Code Playgroud)
但是,这种调用ls也不会产生总大小。
信不信由你,你可以用findand做到这一点du。我使用了一种类似的技术,我曾在我的博客上写过一段时间。那篇文章的标题是:[one-liner]:在 Linux 下使用 du 计算文件列表的磁盘空间使用情况。
该帖子的要点是这样的命令:
$ find -maxdepth 2 -type f | tr '\n' '\0' | du -ch --files0-from=-
Run Code Online (Sandbox Code Playgroud)
这将列出所有文件的大小以及汇总。
$ find -maxdepth 2 -type f | tr '\n' '\0' | du -ch --files0-from=- | tail -10
0 ./92086/2.txt
0 ./92086/5.txt
0 ./92086/14.txt
0 ./92086/19.txt
0 ./92086/18.txt
0 ./92086/17.txt
4.0K ./load.bash
4.0K ./100855/plain.txt
4.0K ./100855/tst_ccmds.bash
21M total
Run Code Online (Sandbox Code Playgroud)
注意:据我所知,此解决方案需要du支持--files0-from=GNU 开关。
摘自 du 手册页
--files0-from=F
summarize disk usage of the NUL-terminated file names specified in
file F; If F is - then read names from standard input
Run Code Online (Sandbox Code Playgroud)
此外,此方法无法处理文件名中的特殊字符,例如空格和不可打印的字符。
du: cannot access `./101415/fileD': No such file or directory
du: cannot access `E': No such file or directory
Run Code Online (Sandbox Code Playgroud)
可以通过引入更多tr .. ..命令来用替代字符替换它们来解决这些问题。但是,如果您可以访问 GNU 的find.
如果您的版本find提供--print0开关,那么您可以使用此咒语来处理具有不可打印的空格和/或特殊字符的文件。
$ find -maxdepth 2 -type f -print0 | du -ch --files0-from=- | tail -10
0 ./92086/2.txt
0 ./92086/5.txt
0 ./92086/14.txt
0 ./92086/19.txt
0 ./92086/18.txt
0 ./92086/17.txt
4.0K ./load.bash
4.0K ./100855/plain.txt
4.0K ./100855/tst_ccmds.bash
21M total
Run Code Online (Sandbox Code Playgroud)
du(磁盘使用)计算文件占用的空间。将您找到的文件传递给它并指示它汇总 ( -c) 并以人类可读的格式 ( -h) 而不是字节计数打印。然后,您将获得所有文件的大小,并以总计结束。如果你只对这最后一行感兴趣,那么你可以tail为它。
为了还处理文件名中的空格,find打印和xargs期望的分隔符被设置为空符号而不是通常的空格。
find -maxdepth 2 -type f -print0 | xargs -0 du -ch | tail -n1
Run Code Online (Sandbox Code Playgroud)
如果您希望找到许多超出最大参数数量的文件,xargs 会将这些文件拆分为多个du调用。然后,你可以解决与更换tail了grep,那只能说明在总结线。
find -maxdepth 2 -type f -print0 | xargs -0 du -ch | grep -P '\ttotal$'
Run Code Online (Sandbox Code Playgroud)