大佬教程收集整理的这篇文章主要介绍了如何在没有find的情况下在linux shell脚本中根据日期查找和删除文件?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在linux sHell脚本中删除超过7天的所有文件.就像是:
FILES=./path/to/dir for f in $FILES do echo "Processing $f file..." # take action on each file. $f store current file name # perhaps stat each file to get the last modified date and then delete files with date older than today -7 days. done
我可以用’stat’来做这件事吗?我试图用
find *.gz -mtime +7 -delete
但发现我不能在目标系统上使用find(没有cron用户的权限,这不能更改).目标系统是Redhat Enterprise.
文件名的格式如下:
gzip> / mnt / target03 / rest-of-path / web / BACkups / DATABASename_date“%Y-%m-%d”.gz
此脚本获取自纪元以来的当前时间(以秒为单位),然后计算7天前的时间戳.然后,对于每个文件,解析文件名并将每个文件名中嵌入的日期转换为时间戳,然后比较时间戳以确定要删除的文件.使用时间戳消除了直接处理日期的所有麻烦(闰年,几个月不同的日子等)
#funciton to get timestamp X days prior to input timestamp # arg1 = number of days past input timestamp # arg2 = timestamp ( e.g. 1324505111 ) seconds past epoch gettimestamPDAysInPast () { daysinpast=$1 seconds=$2 while [ $daysinpast -gt 0 ] ; do daysinpast=`expr $daysinpast - 1` seconds=`expr $seconds - 86400` done # make midnight mod=`expr $seconds % 86400` seconds=`expr $seconds - $mod` echo $seconds } # get current time in seconds since epoch getCurrentTime() { echo `date +"%s"` } # parse format and convert time to timestamp # e.g. 2011-12-23 -> 1324505111 # arg1 = filename with date String in format %Y-%m-%d getFiletimestamp () { filename=$1 date=`echo $filename | sed "s/[^0-9\-]*\([0-9\-]*\).*/\1/g"` ts=`date -d $date | date +"%s"` echo $ts } ########################### MAIN ############################ # Expect directory where files are to be deleted to be first # arg on commandline. If not provided then use current working # directory FILEDIR=`pwd` if [ $# -gt 0 ] ; then FILEDIR=$1 fi cd $FILEDIR Now=`getCurrentTime` mustBeBefore=`gettimestamPDAysInPast 7 $Now` SAVEIFS=$IFS # need this to loop around spaces with filenames IFS=$(echo -en "\n\b") # for safety change this glob to something more reStrictive for f in * ; do filetime=`getFiletimestamp $f` echo "$filetime lt $mustBeBefore" if [ $filetime -lt $mustBeBefore ] ; then # uncomment this when you have tested this on your system echo "rm -f $f" fi done # only need this if you are going to be doing something else IFS=$SAVEIFS
以上是大佬教程为你收集整理的如何在没有find的情况下在linux shell脚本中根据日期查找和删除文件?全部内容,希望文章能够帮你解决如何在没有find的情况下在linux shell脚本中根据日期查找和删除文件?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。