【问题标题】:Remove empty files and save a list of deleted files删除空文件并保存已删除文件的列表
【发布时间】:2022-01-18 21:21:28
【问题描述】:

我需要一个删除所有空文件并将已删除文件列表写入文本文件的脚本。

删除文件有效。不幸的是,该列表不起作用。

find . -type f -empty -print -delete

我尝试过这样的事情:

-print >> test.txt

【问题讨论】:

  • 为我工作。你得到什么输出?
  • @joanis 是的,它有效。我得到了输出。但我想把它发送到一个文件中。这意味着 - 每个已删除的文件 -> 其名称保存在 test.txt 文件中
  • 啊,有趣的问题:当我将输出重定向到. 中的文件时,命令本身会在写入任何内容之前将其删除,因此它丢失了。试试find . -type f -empty -print -delete > ../output

标签: bash shell gnu-findutils


【解决方案1】:

当我将您的命令输出重定向到 . 中的文件时,它会在写入任何内容之前被 find 命令删除,因为它是空的。

要解决这个问题,请确保输出文件一开始不为空,或者将其保存在其他地方:

find . -type f -empty -print -delete > ../log

date > log
find . -type f -empty -print -delete >> log

或者,改编自@DanielFarrell 的评论:

find . -type f -empty -a -not -wholename ./log  -print -delete > log

添加的-a -not -wholename ./log./log 排除在查找操作之外。

【讨论】:

  • 或者用-not -name log排除
  • 也许{ date; find . -type f -empty -print -delete; } > log 可以用来记录动作的时间戳。
  • @glennjackman 这似乎是个好主意,但我想知道当 find 到达它时日志是否仍然是空的,因为管道中的输出缓冲。但是,date > log; find ... >> log 可以可靠地工作。
  • 对,好点。
【解决方案2】:

您可以在 rm 命令中使用 -exec 选项而不是 -delete。

find . -type f -emtpy -exec rm --verbose {} \; >> logfile.txt

日志文件.txt:

removed './emptyfile1'
removed './emptyfile0'

或者您可以使用管道和 xargs 来获得更干净的输出:

find . -type f -empty | xargs ls | tee -a logfile.txt | xargs rm

这只会给你删除的文件名。

【讨论】:

  • 当我运行这些命令中的任何一个时,logfile.txt 仍然会被删除,除非 if 在 find 开始之前已经非空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-04
  • 1970-01-01
  • 1970-01-01
  • 2011-08-13
  • 2018-01-21
  • 1970-01-01
相关资源
最近更新 更多