1

和:

Find="$(find / -name "*.txt" )"
du -hc "$Find" | tail -n1
echo "$Find" | xargs rm -r

如果foo bar.txt找到该文件,则不会将其与 du 一起计算或删除该文件。逃离空间的最佳方法是什么?

4

2 回答 2

1

如果您的文件名都没有嵌入换行符(这将是非常不寻常的),您可以使用以下内容:

注意:为防止在试验命令时意外删除文件,我已将其替换/为输入目录。(如问题中所用)与/foo.

# Read all filenames into a Bash array; embedded spaces in
# filenames are handled correctly.
IFS=$'\n' read -d '' -ra files < <(find /foo -name "*.txt")

# Run the `du` command:
du -hc "${files[@]}" | tail -1

# Delete the files.
rm -r "${files[@]}"

请注意,如果您不需要提前收集所有文件名并且不介意运行两次,您可以为每个任务find使用一个命令(管道到 除外),这也是最强大的选项(唯一的警告是如果你有太多的文件,它们不适合单个命令行,可以多次调用findtaildu

# The `du` command
find /foo -name "*.txt" -exec du -hc {} + | tail -n1

# Deletion.
# Note that both GNU and BSD `find` support the `-delete` primary,
# which supports deleting both files and directories.
# However, `-delete` is not POSIX-compliant (a POSIX-compliant alternative is to
# use `-exec rm -r {} +`).
find /foo -name "*.txt" -delete

使用+终止传递给的命令-exec至关重要,因为它指示 find将尽可能多的匹配项传递给目标命令;通常,但不一定,这会导致一次调用;实际上-exec ... +就像一个内置的xargs,除了参数中嵌入的空格不是问题。

换句话说:-exec ... +不仅比管道更健壮xargs,而且 - 由于不需要管道和另一个实用程序 - 也更有效。

于 2016-02-04T21:33:27.833 回答
0

也许find / -name '*.txt' -exec du -hc {} \;更像你正在寻找的东西?

但是,按照您的做法进行操作,您在调用 时会丢失引号,并且在不起作用时会du不必要地使用……您似乎迷恋,谁不是您的朋友。xargsecho

由于\0文件名中不允许使用,因此您可以find使用其-print0选项安全地收集结果:

 date > /private/var/mobile/Documents/Local\ Cookies/Clean

 find . -print0 | while IFS='' read -r -d '' file
 do
      du -hc "$file" | tail -n 1
      rm "$file"
 done

更正后应该现在可以在 MacOS 和 Linux 上运行。

于 2016-02-04T21:27:41.490 回答