如何删除超过 (n) 天的文件但保留 (n) 个文件而不考虑年龄? [英] How can I delete files over (n) days old but leave (n) files regardless of age?

查看:19
本文介绍了如何删除超过 (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=""; secs=systime()-(days*24*60*60) }
    (NR>cnt) && ($1>secs) { print gensub(/S+s+/,"",1) }
' |
xargs -0 ls --

完成测试后将 ls 更改为 rm 并确保它为您提供预期的输出.

Change ls to rm when you're done testing and sure it's giving you the expected output.

这篇关于如何删除超过 (n) 天的文件但保留 (n) 个文件而不考虑年龄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆