尝试 grep find -print0 会导致奇怪的行为

Trying to grep a find -print0 causes strange behavior

我有一个文件夹 directories/files,它们的名称中有空格,我想将所有 *.ttf 文件复制到另一个目录 ,文件夹 ConsolasSystem Volume Information。在 this post 之后,我尝试了:

find ... -print0  | grep -v "System Volume Information" --null | grep -v "Consolas" --null | xargs -0 cp -t destination

出于某种原因,这会导致来自第一个 grep 的 Binary file (standard input) matches 消息。使用 egrep 组合过滤器,我尝试了:

find . -name '*.ttf' -print0 | egrep -v "(System Volume Information)|(Consolas)" --null | xargs...

但在这种情况下,egrep 将向终端输出 nothing,即使除了 System Volume InformationConsolas 之外还有很多其他文件夹。当我删除命令的 find 部分以外的所有部分时,由于 -print0 选项,我得到了一大块没有换行符的文本。由于整个块包括 Consolas,通过省略它我省略了 一切 。当我尝试对结果执行 grep Arial 并且打印出整个块时,我确认了这一点。

我应该如何防止 grep 中的这种行为?

这是使用 grep 的“-v”选项的预期行为。它通过不给您任何包含 Consolas 的行来执行您告诉它的操作。为避免这种情况,请不要将 -print0 和 post 进程与 xargs 一起使用(正如您已经发现的那样),或者如果您确实需要 运行 一切都在 'grep -v' 过滤器之后通过像这样:

echo -n $(find . -name '*.ttf' | grep -v "System Volume Information" --null | grep -v "Consolas" --null)

但您可能不需要它来解决这个问题,因为 xargs 就足够了。