如何删除许多(200 000)个文件?

FMa*_*008 17 ubuntu shell terminal remove

我必须从文件夹中删除 200 000 个文件(所有这些文件),而且我不想删除文件夹本身。

使用 rm,我收到“参数列表太长”错误。我试图用 xargs 做一些事情,但我不是一个 Shell Guy,所以它不起作用:

find -name * | xargs rm -f
Run Code Online (Sandbox Code Playgroud)

qua*_*nta 36

$ find /path/to/folder -type f -delete
Run Code Online (Sandbox Code Playgroud)

  • 值得一提的是,GNU find(大多数Linux发行版使用)可以使用`-delete`自行删除文件。这也避免了包含引号或换行符的文件的问题(尽管您可以使用 GNU find 的 `-print0` 和 GNU xarg 的 `-0` 选项来解决这个问题)。 (15认同)
  • @DerfK,好话!此外,许多 ppl 倾向于使用 `xargs` 而 `find` 具有 `-exec command {} +` 语法。 (3认同)

dto*_*lis 5

你做的一切都是正确的。是'*'给您带来问题(shell 将其扩展为文件列表而不是find)。正确的语法可能是:

cd <your_directory>; find . -type f | xargs rm -f
find <your_directory> -type f | xargs rm -f
Run Code Online (Sandbox Code Playgroud)

(后者效率稍低,因为它会将更长的名称传递给xargs,但您几乎不会注意到:-))

或者,您可以像这样转义您的'*'(但是在这种情况下,它也会尝试删除“.”和“..”;这不是什么大问题-您只会收到一点警告:-)):

find . -name '*' | xargs rm -f
find . -name "*" | xargs rm -f
find . -name \* | xargs rm -f
Run Code Online (Sandbox Code Playgroud)

如果您的文件名包含空格,请使用以下命令:

find . -type f -print0 | xargs -0 rm -f
Run Code Online (Sandbox Code Playgroud)