Move logfiles based on filename (date) with bash

Viewed 100

I am currently looking to automate backups of old logfiles. I tried a lot with find, however it seems that its only possible to go by edit date. Tried this:

find /tmp/logtest -ctime +14 | xargs -I '{}' mv {} /mnt/archive

What I am looking for is moving based on filename.

My folder looks like this

.
├── 20200901.cq4.gz
├── 20200902.cq4.gz
├── 20200903.cq4.gz
├── 20200904.cq4.gz
├── 20200905.cq4.gz
├── 20200906.cq4.gz
├── 20200907.cq4.gz
├── 20200908.cq4.gz
├── 20200909.cq4.gz
├── 20200910.cq4.gz
├── 20200911.cq4.gz
├── 20200912.cq4.gz
├── 20200913.cq4.gz
├── 20200914.cq4.gz
├── 20200915.cq4.gz
├── 20200916.cq4.gz
├── 20200917.cq4.gz
├── 20200918.cq4.gz
├── 20200919.cq4.gz
├── 20200920.cq4.gz
├── 20200921.cq4.gz
├── 20200922.cq4.gz
├── 20200923.cq4.gz
├── 20200924.cq4.gz
├── 20200925.cq4.gz
├── 20200926.cq4.gz
├── 20200927.cq4.gz
├── 20200928.cq4.gz
├── 20200929.cq4.gz
├── 20200930.cq4.gz
├── 20201001.cq4.gz
├── 20201002.cq4.gz
├── 20201003.cq4.gz
├── 20201004.cq4.gz
├── 20201005.cq4.gz
├── 20201006.cq4
├── chrongzip.sh

All the files are tagged with date in scheme YYYYMMDD.cq4.gz (they're getting gunzipped after 1 day). What I want to do is moving files older than 14 days to /mnt/archive. Is there an easy way to achieve this?

2 Answers

I would suggest something like this:

date="$(date -d "14 days ago" "+%Y%m%d")"
for file in 2*.cq4.gz; do [ "${file%%.*}" -gt "$date" ] || mv -- "$file" /mnt/archive/; done

You can write a script extracting the date from the file name and comparing it to the current date (translation in seconds to make the comparisons) :

    #!/bin/sh

    CUR_DATE_S=`date +%s`

    MAX_DIFF_S=`expr 14 \* 24 \* 3600`

    ls *.cq4.gz | while read fname
    do
      FILE_DATE=`echo $fname | cut -d. -f1`
      FILE_DATE_S=`date +%s --date ${FILE_DATE}`
      DIFF_S=`expr ${CUR_DATE_S} - ${FILE_DATE_S}`

      if [ ${DIFF_S} -gt ${MAX_DIFF_S} ]
      then
        echo Archive $fname
      fi
    done
Related