log文件的文件名中带上其生成的时间日期是很常见的设计,经常需要以一定的时间阈值(threshold)来对一些旧日志文件做一些处理。如果是按天数为单位处理,也可以借助`find`命令(-mtime),但细粒度的时间处理,就得手动从log文件名中提取时间日期数据然后再做过滤操作。
#!/usr/bin/env bash
# Author : 蛙鳜鸡鹳狸猿
# create_ts : 2019-06-06
# program : Get expired files
function get_obj_ts() {
# Get 14-length-long timestamp from namespace of OS directory/file path
# $1: OS directory/file path
local ts=$(echo $1 | grep -Go '[[:digit:]]\{14\}')
if [[ -n ${ts} ]]; then
echo ${ts}
else
echo ""
fi
}
function check_time_threshold() {
# Check whether obj out of specified time threshold or not
# $1 left time args
# $2 right time args
# $3 time threshold
if [[ $(($1-$2)) -gt $3 ]]; then
return 1
fi
}
function get_overtime_obj() {
# Get over time obj
# $1: OS directory path
# $2 time threshold
local get_obj=""
for obj in $(ls $1)
do
local ts=$(get_obj_ts ${obj})
if [[ -n ${ts} ]]; then
check_time_threshold $(date +%Y%m%d%H%M%S) ${ts} $2
if [[ $? -eq 1 ]]; then
get_obj=${get_obj}'\n\t'"$1/${obj}"
fi
fi
done
echo ${get_obj}
}