bash 基于 CreationTime 删除文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10169881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:02:24  来源:igfitidea点击:

Deleting files based on CreationTime

linuxbashunixunix-timestamp

提问by user680204

In a directory there are files which are generated daily. Format of files, if its generated on 16th Apr 2012 is TEST_20120416.

在一个目录中有每天生成的文件。文件格式,如果它是在 2012 年 4 月 16 日生成的,则为 TEST_20120416。

So I need to delete all the files which are older than 7 days. I tried doing this

所以我需要删除所有超过 7 天的文件。我试过这样做

#!/bin/ksh
find /data/Test/*.* -mtime -7 -exec rm -rf {} \;
exit 0

Now the problem is above code is deleting based on modification time but according to requirement file should delete based on creation time.Kindly help me out in deleting files based on filename(filename has timestamp).

现在问题是上面的代码是根据修改时间删除,但根据要求文件应该根据创建时间删除。请帮助我根据文件名删除文件(文件名有时间戳)。

回答by RobertT

As you fortunately have creation date encoded in filename, this should work:

幸运的是,您在文件名中编码了创建日期,这应该可以工作:

#!/bin/sh
REFDATE=$(date --date='-7 days' +%Y%m%d)
PREFIX=TEST_
find /data/Test/ -name $PREFIX\* | while read FNAME; do
   if [ ${FNAME#$PREFIX} -lt $REFDATE ]; then
       rm $FNAME
   fi
done

It will print warnings if you have some other files with names starting with TEST_ in which case some more filtering may be needed.

如果您有其他一些名称以 TEST_ 开头的文件,它会打印警告,在这种情况下可能需要进行更多过滤。

回答by Divanshu

find /data/Test/*.* -ctime -7 -delete

'find /data/Test/.' will find the all the files in the /data/Test folder and argument '-ctime -7' will limit the search to the creation time to last 7 days and -delete option will delete such files

'找到/数据/测试/ ' 将找到 /data/Test 文件夹中的所有文件,参数 '-ctime -7' 将搜索限制为创建时间为过去 7 天,-delete 选项将删除此类文件