如果文件修改日期早于N天 [英] If file modification date is older than N days

查看:61
本文介绍了如果文件修改日期早于N天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果文件的修改日期早于许多天,则此问题与采取措施有关.我确信对于创建日期或访问日期,如果有的话,对于修改日期,它是相似的.

This question pertains to taking action if a file has a modification date older than so many days. I'm sure it would be similar for creation date or access date, but for modification date, if I have:

file=path-name-to-some-file
N=100  # for example, N is number of days

我该怎么办

if file modification time is older than N days
then
fi

推荐答案

有几种方法.一种只是要求 find 为您进行过滤:

Several approaches are available. One is just to ask find to do the filtering for you:

if [[ $(find "$filename" -mtime +100 -print) ]]; then
  echo "File $filename exists and is older than 100 days"
fi


另一种方法是使用GNU日期进行数学运算:


Another is to use GNU date to do the math:

# collect both times in seconds-since-the-epoch
hundred_days_ago=$(date -d 'now - 100 days' +%s)
file_time=$(date -r "$filename" +%s)

# ...and then just use integer math:
if (( file_time <= hundred_days_ago )); then
  echo "$filename is older than 100 days"
fi


如果您具有GNU统计信息,则可以从秒开始请求文件的时间戳(以秒为单位),然后自己做一些数学运算(尽管这在边界情况下可能会有些偏离,因为它是在计算秒数,而不是考虑到leap日等因素,而不是四舍五入到一天的开始):


If you have GNU stat, you can ask for a file's timestamp in seconds-since-epoch, and do some math yourself (though this will potentially be a bit off on the boundary cases, since it's counting seconds -- and not taking into account leap days and such -- and not rounding to the beginning of a day):

file_time=$(stat --format='%Y' "$filename")
current_time=$(( date +%s ))
if (( file_time < ( current_time - ( 60 * 60 * 24 * 100 ) ) )); then
  echo "$filename is older than 100 days"
fi


如果需要支持非GNU平台,另一种选择是使用Perl(我将其留给其他人演示).


Another option, if you need to support non-GNU platforms, is to shell out to Perl (which I'll leave it to others to demonstrate).

如果您更感兴趣的是从文件中获取时间戳信息以及围绕该文件的可移植性和鲁棒性约束,请参见

If you're interested more generally in getting timestamp information from files, and portability and robustness constraints surrounding same, see also BashFAQ #87.

这篇关于如果文件修改日期早于N天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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