从没有最后三个的子文件夹中删除文件

remove files from subfolders without the last three

我有这样的结构:

/usr/local/a/1.txt
/usr/local/a/2.txt
/usr/local/a/3.txt
/usr/local/b/4.txt
/usr/local/b/3.txt
/usr/local/c/1.txt
/usr/local/c/7.txt
/usr/local/c/6.txt
/usr/local/c/12.txt
...

我想删除子目录下的所有文件*.txt,除了修改日期最大的最后三个文件,但是我在当前目录下

ls -tr *.txt | head -n-3 |xargs rm -f

我需要将其与代码结合起来:

find /usr/local/**/* -type f 

我应该使用 maxdepth 选项吗?

感谢您的帮助, 奥拉

添加了 maxdepth 选项以查找一级,按最后修改时间排序文件,tail 忽略最早修改的 3 个文件,xargs-r仅在找到文件时删除文件。

 for folder in $(find /usr/local/ -type d)
 do     
     find $folder -maxdepth 1 -type f -name "*.txt" | xargs -r ls -1tr | tail -n+3 | xargs -r rm -f
 done

运行 上面的命令一次没有 rm 以确保前面的命令选择正确的文件进行删除。

您几乎找到了解决方案:使用 find 获取文件,ls 按修改日期对它们进行排序,并 tail 省略三个最近修改的文件:

find /usr/lib -type f | xargs ls -t | tail -n +4 | xargs rm

如果您只想删除指定深度的文件,请添加 -mindepth 4 -maxdepth 4 以查找参数。

可以使用find的-printf选项,在文件名前打印修改时间,然后排序去掉日期。这完全避免了使用 ls。

find /usr/local -type f -name '*.txt' -printf '%T@|%p\n' | sort -r | cut -d '|' -f 2 | head -n-3 | xargs rm -f

使用 xargs ls -t 的其他答案可能导致不正确的结果,当结果多于 xargs 可以放入单个 ls -t 命令时。

但是对于每个子文件夹,所以当我有

/usr/local/a/1.txt
/usr/local/a/2.txt
/usr/local/a/3.txt
/usr/local/a/4.txt
/usr/local/b/4.txt
/usr/local/b/3.txt
/usr/local/c/1.txt
/usr/local/c/7.txt
/usr/local/c/6.txt
/usr/local/c/12.txt

我想分别为每个子文件夹使用代码

head -n-3 |xargs rm -f

所以我敢打赌,如果我按日期排序,那么要删除的文件:

/usr/local/a/4.txt
/usr/local/c/12.txt

我想在任何子文件夹中留下三个最新的文件