【问题标题】:piping empty find result to du through xargs results in unexpected behavior通过 xargs 将空查找结果管道传输到 du 会导致意外行为
【发布时间】:2014-01-24 17:27:53
【问题描述】:

我想出了一个命令来查找文件并使用 find、xargs 和 du 打印它们的大小。当我搜索不存在的东西时遇到问题。使用 xargs 方法,当某些内容不存在时,du 会报告所有文件夹,但我希望它不会报告任何内容,因为应该找不到任何内容。使用 -exec 方法时,它可以正常工作,但是根据我在更大搜索中阅读和观察的内容,它的效率较低,因为它对找到的每个文件重复 du 命令,而不是对找到的文件组进行操作。请参阅它提到的部分 -delete:http://content.hccfl.edu/pollock/unix/findcmd.htm

这是一个例子。首先,这是目录中的内容:

ls
bar_dir/ test1.foo test2.foo test3.foo

ls bar_dir
test1.bar test2.bar test3.bar

以下是我希望找到结果的两个搜索:

find . -name '*.foo' -type f -print0 | xargs -0 du -h
4.0K ./test2.foo
4.0K ./test1.foo
4.0K ./test3.foo

find . -name '*.bar' -type f -print0 | xargs -0 du -h
4.0K ./bar_dir/test1.bar
4.0K ./bar_dir/test2.bar
4.0K ./bar_dir/test3.bar

这是一个我不希望有结果的搜索,但我得到了一个目录列表:

find . -name '*.qux' -type f -print0 | xargs -0 du -h
16K ./bar_dir
32K .

如果我只使用 find,它不会返回任何内容(如预期的那样)

find . -name '*.qux' -print0

如果我对 du 使用 -exec 方法,它也不会返回任何内容(如预期的那样)

find . -name '*.qux' -type f -exec du -h '{}' \;

那么当 find 没有找到任何东西时,xargs du 方法有什么问题呢?感谢您的宝贵时间。

【问题讨论】:

    标签: linux find xargs du


    【解决方案1】:

    你看du --files0-from -了吗?

    来自man 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
    

    试试这样:

    find . -name '*.qux' -type f -print0 | du -h --files0-from -
    

    【讨论】:

    • 这适用于较小的编辑...在-I{} 之间添加一个空格:find . -name '*.qux' -type f -print0 | xargs -0 -I {} du -h {} 谢谢!附带说明一下,我尝试了没有-print0-0 的原始代码,并且仍然返回了目录。此代码:find . -name '*.qux' -type f -print | xargs du -h 仍然不起作用。
    • 这也有效:find . -name '*.qux' -type f -print0 | du -h --files0-from - 我将阅读这两个解决方案。再次感谢!
    • 在我有限的测试中,--files0-from - 方法似乎更快。
    猜你喜欢
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多