Shell脚本:根据文件名中日期时间字符筛选过期文件

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}
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值