Hailwood
Hailwood

Reputation: 92691

Get list of files where date older than 7 days?

I have a script that creates mysql backups, the files end up being called.

DB_name-M_D_Y.gz so for example stackoverflow_users-04_10_2013.gz

Now I don't know the name of the files before hand, just the pattern.

What I need to do is adapt the script to, before it creates new backups, check if the date in any of the files is older that 7 days, if so do other things with those.

I know how to do the other things, but getting the list of files in the first place is the difficult one.

I cannot just use the modified date as the files get touched by other scripts so need to read the date from the file name.

So, How can I get a list of the files?


For replying to comments assume this dummy data

Current Date: 10th April 2013

database zero-03_31_2013.gz    #Older | Notice this one has spaces
database_one-04_01_2013.gz     #Older
database_two-04_02_2013.gz     #Older
database_three-04_03_2013.gz   #Newer | Actually 7 days, but we want OLDER than!
database_four-04_04_2013.gz    #Newer
database_five-04_05_2013.gz    #Newer
dater.sh                       #Does not have the .gz extension | Not deleted

Bash Version

matthew@play:~/test$ bash --version
GNU bash, version 4.2.37(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Upvotes: 0

Views: 2277

Answers (1)

dogbane
dogbane

Reputation: 274888

Try the following script:

#!/bin/bash

# get the date 7 days ago
sevenDaysAgo=$(date -d "-7 day 00:00:00" +%s)

# create an array to hold the files older than 7 days
result=()

# loop over the files
while IFS= read -d $'\0' -r file
do
    # extract the date from each filename using a regex
    if [[ $file =~ ^.*-([0-9]+)_([0-9]+)_([0-9]+).gz$ ]]
    then
        m="${BASH_REMATCH[1]}"
        d="${BASH_REMATCH[2]}"
        y="${BASH_REMATCH[3]}"
        fileDateTime="$(date -d ${y}${m}${d} +%s)"

        # check if the date is older than 7 days ago
        if (( fileDateTime < sevenDaysAgo ))
        then
            result+=( "$file" )
        fi
    fi
done < <(find . -type f -name "*.gz" -print0)

# print out the results for testing
for f in "${result[@]}"
do
    echo "$f"
done

Upvotes: 5

Related Questions