目录树中从最旧到最新的文件并以交互方式删除每个文件

目录树中从最旧到最新的文件并以交互方式删除每个文件

在步骤 1 中,我尝试“查找”目录树中最旧的文件,我通过以下方法解决了这个问题这个问题

现在我想以xargs从最旧到最新的方式交互删除。

因为这find -type f -printf '%T+ %p\n' | sort | xargs -0 -d '\n' rm -i不起作用。我在另一篇文章中看到了, find . -type f -print0 | xargs -0 ls -rtxargs遗憾的是,添加到它不起作用。

pi@raspberrypi:/usr/share/doc/samba$ find . -type f -print0 | xargs -0 ls -rt | xargs -0  -d '\n' rm -i
    rm: remove write-protected regular file ‘./examples/LDAP/samba.schema.oc.IBM-DS’? rm: remove write-protected regular file ‘./examples/LDAP/samba-schema-netscapeds5.x.README’? rm: remove write-protected regular file ‘./examples/LDAP/samba-schema.IBMSecureWay’? rm: remove write-protected regular file ‘./examples/LDAP/samba.schema.gz’? rm: remove write-protected regular file ‘./examples/LDAP/samba-schema-FDS.ldif.gz’? rm: remove write-protected regular file ‘./examples/LDAP/samba.schema.at.IBM-DS.gz’? rm: remove write-protected regular file ‘./examples/LDAP/samba-nds.schema.gz’? rm: remove write-protected regular file ‘./examples/LDAP/samba.ldif.gz’? rm: remove write-protected regular file ‘./examples/LDAP/ol-schema-migrate.pl.gz’? rm: remove write-protected regular file ‘./examples/LDAP/get_next_oid’? rm: remove write-protected regular file ‘./README.Debian’? rm: remove write-protected regular file ‘./TODO.Debian’? rm: remove write-protected regular file ‘./NEWS.Debian.gz’? rm: remove write-protected regular file ‘./copyright’? rm: remove write-protected regular file ‘./changelog.Debian.gz’? rm: remove write-protected regular file ‘./examples/LDAP/README’?

请注意这不是权限问题。我使用这个/usr/share/doc/samba作为示例以避免发布我的真实文件名。

在网上搜索,我找不到任何递归(整个树)、处理空白文件字符且具有交互性的脚本。所以我做了这个。这不会处理所有类型的特殊字符。所以任何改进都会被接受。

#!/bin/bash
find -type f -printf '%T+ %p\n' | sort | head -n 3 > /tmp/1
cut -c32- /tmp/1 | awk '{print "rm -i", "\""$_"\""}'/tmp/2
bash /tmp/2

答案1

我看到的脚本中唯一有问题的字符是"和换行符。您不必太担心文件名中的换行符。

您可能想要使用不同的临时文件名,例如$$文件名中带有。

那么,作为改进:

#!/bin/bash
TMP1=/tmp/file1.$$
TMP2=/tmp/file2.$$
find -type f -printf '%T+ %p\n' | sort | head -n 3 > $TMP1
cat $TMP1 | sed 's/"/\\"/g;s/[^ ]* //;s/^/rm -i "/;s/$/\"/' >$TMP2
bash $TMP2
rm -f $TMP1 $TMP2

这应该可以处理文件名中的引号。(注意:脚本仍然存在一些问题。不过,在您自己的家庭环境中执行此操作是可以的。不建议使用大写的 TMP,但我还是这样做了。)

注意:xargs -p当文件名中带有空格时将不起作用。

答案2

你几乎就到了。

这将执行您想要的操作并处理文件名中的空格:

find -type f -printf '%T+ %p\n' | sort | cut -c32- | xargs -p -n1 -d '\n' rm

-p, --interactive:提示用户是否运行每个命令行并从终端读取一行。仅当响应以 y 或 Y 开头时才运行命令行。

-n max-args, --max-args=max-args:每个命令行最多使用 max-args 个参数。

-d delim输入项以指定字符终止。

相关内容