如何删除超过 (n) 天的文件但保留 (n) 个文件而不考虑年龄? [英] How can I delete files over (n) days old but leave (n) files regardless of age?
本文介绍了如何删除超过 (n) 天的文件但保留 (n) 个文件而不考虑年龄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 PHP 中编写了以下内容,但我想知道是否有一种优雅的方法可以在 Linux shell 脚本中执行此操作?基本上删除 (n) 天前的文件,但保留 (n) 最新的文件,无论年龄大小.
I wrote the following in PHP but I was wondering if there is an elegant way to do this in a Linux shell script? Basically delete files over (n) days old, but leave the (n) newest files regardless of age.
PHP
foreach (glob("backup/*.db") as $file) {
$a[$file]=date("Y-m-d",filemtime($file));
}
$i=0;
arsort($a);
foreach($a as $file=>$date) {
if ($i++>=10) {
if ($date<=date("Y-m-d",strtotime("-10 days"))) {
unlink($file);
xmessage("PURGED: $file");
}
}
}
我的想法是用find -mtime +(n) exec rm"删除但只在不在head -n +(n)"中的文件中使用管道?但是head -n"似乎并没有像我想的那样做.谢谢.
My idea was to delete with "find -mtime +(n) exec rm" but only pipe in the files that are NOT in "head -n +(n)"? But "head -n" does not seem to do what I thought it would. Thanks.
SHELL SCRIPT
find -mtime +10 | ls -t *.DB.tar.gz | head -n -10
推荐答案
使用所有 GNU find、sort、awk 和 xargs 试试这个:
Try this using all GNU find, sort, awk, and xargs:
find . -type f -printf '%Ts %p ' |
sort -k1,1nr -sz |
awk -v days=10 -v cnt=10 '
BEGIN { RS=ORS="