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

查看:59
本文介绍了如何删除(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\0' |
sort -k1,1nr -sz |
awk -v days=10 -v cnt=10 '
    BEGIN { RS=ORS="\0"; 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天全站免登陆