linux文件没有日期,如何在没有find的情况下在linux shell脚本中根据日期查找和删除文件?...

由于你在文件名中有时间,然后使用它来删除时间,这是一些代码:

此脚本获取自纪元以来的当前时间(以秒为单位),然后计算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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值