首页 > 解决方案 > 使用 Shell 清理十天或更早的日志

问题描述

   [root@amp logs]# ls -l
    total 0
    -rw-r--r-- 1 root root 0 Nov 23 17:51 lb-quarzcenter.log
    -rw-r--r-- 1 root root 0 Feb 27 17:26 lb-quarzcenter.log.2019-02-01
    -rw-r--r-- 1 root root 0 Feb 27 17:26 lb-quarzcenter.log.2019-02-02
    -rw-r--r-- 1 root root 0 Feb 27 17:26 lb-quarzcenter.log.2019-02-03
    -rw-r--r-- 1 root root 0 Feb 27 17:26 lb-quarzcenter.log.2019-02-04
    -rw-r--r-- 1 root root 0 Feb 27 17:26 lb-quarzcenter.log.2019-02-05
    -rw-r--r-- 1 root root 0 Feb 27 17:26 lb-quarzcenter.log.2019-02-06
    -rw-r--r-- 1 root root 0 Feb 27 17:26 lb-quarzcenter.log.2019-02-07
    -rw-r--r-- 1 root root 0 Feb 27 17:26 lb-quarzcenter.log.2019-02-08
    -rw-r--r-- 1 root root 0 Feb 27 17:26 lb-quarzcenter.log.2019-02-10
    -rw-r--r-- 1 root root 0 Feb 27 17:26 lb-quarzcenter.log.2019-02-11
    -rw-r--r-- 1 root root 0 Feb 27 17:26 lb-quarzcenter.log.2019-02-12
    -rw-r--r-- 1 root root 0 Feb 27 17:26 lb-quarzcenter.log.2019-02-13
    -rw-r--r-- 1 root root 0 Feb 27 17:26 lb-quarzcenter.log.2019-02-14
    -rw-r--r-- 1 root root 0 Nov 23 17:51 lb-quarzcenter.log.2019-02-15
    -rw-r--r-- 1 root root 0 Feb 27 17:26 lb-quarzcenter.log.2019-02-09

如何将字符串与年-月-日匹配并删除 10 天前的文件lb-quarzcenter.log.*

标签: bashshellsh

解决方案


now=$(date +%s)                                  # express current time as seconds since 1970-01-01
(( ten_days_ago = now - 60*60*24*10 ))           # subtract 864000 seconds (10 days) from that
date_minus_ten=$(date +%F --date="@$ten_days_ago")  # express that number as a YYYY-MM-DD
for filename in lb-quartzcenter.log.* ; do       # loop over all matching files
    filedate="${filename/lb-quartzcenter.log./}" # remove the filename part before the timestamp
    if [[ $filedate < $date_minus_ten ]] ; then  # if filename remainder is lexicographically lower...
        rm -f "$filename"                        # ... remove the file
    fi
done

推荐阅读