根据文件名作为日期,删除所有30天以上的文件 [英] Delete all files older than 30 days, based on file name as date

查看:340
本文介绍了根据文件名作为日期,删除所有30天以上的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是bash的新手,我有一个任务是删除所有30天以上的文件,我可以根据文件名Y_M_D.ext 2019_04_30.txt来解决这个问题.

I'm new to bash, I have a task to delete all files older than 30 days, I can figure this out based on the files name Y_M_D.ext 2019_04_30.txt.

我知道我可以在包含文件的文件夹中使用ls列出所有文件.我知道我可以使用$ date获取今天的日期,并可以对其进行配置以匹配文件格式$ date "+%Y_%m_%d"

I know I can list all files with ls in a the folder containing the files. I know I can get todays date with $ date and can configure that to match the file format $ date "+%Y_%m_%d"

我知道我可以使用rm删除文件.

I know I can delete files using rm.

如何将所有这些内容捆绑到一个bash脚本中,该脚本可以删除从今天起30天之前的文件?

How do I tie all this together into a bash script that deletes files older than 30 days from today?

在伪python代码中,我想它看起来像:

In pseudo-python code I guess it would look like:

for file in folder:
    if file.name to date > 30 day from now:
        delete file

推荐答案

我绝不是系统管理员,但是您可以考虑以下简单的shell脚本:

I am by no means a systems administrator, but you could consider a simple shell script along the lines of:

# Generate the date in the proper format
discriminant=$(date -d "30 days ago" "+%Y_%m_%d")

# Find files based on the filename pattern and test against the date.
find . -type f -maxdepth 1 -name "*_*_*.txt" -printf "%P\n" |
while IFS= read -r FILE; do
    if [ "${discriminant}" ">" "${FILE%.*}" ]; then
        echo "${FILE}";
    fi
done

请注意,专业人员可能会将其视为外行"解决方案.也许awk可以更好地处理此问题,但不幸的是我不习惯使用它.

Note that this is will probably be considered a "layman" solution by a professional. Maybe this is handled better by awk, which I am unfortunately not accustomed to using.

这篇关于根据文件名作为日期,删除所有30天以上的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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