linuxbash

Delete all files older than 30 days, based on file name as date


I'm new to bash, I have a task to delete all files older than 30 days, I can figure this out based on the files name Y_M_D.ext 2019_04_30.txt.

I know I can list all files with ls in a the folder containing the files. I know I can get todays date with $ date and can configure that to match the file format $ date "+%Y_%m_%d"

I know I can delete files using rm.

How do I tie all this together into a bash script that deletes files older than 30 days from today?

In pseudo-python code I guess it would look like:

for file in folder:
    if file.name to date > 30 day from now:
        delete file

Solution

  • I am by no means a systems administrator, but you could consider a simple shell script along the lines of:

    # Generate the date in the proper format
    discriminant=$(date -d "30 days ago" "+%Y_%m_%d")
    
    # Find files based on the filename pattern and test against the date.
    find . -type f -maxdepth 1 -name "*_*_*.txt" -printf "%P\n" |
    while IFS= read -r FILE; do
        if [ "${discriminant}" ">" "${FILE%.*}" ]; then
            echo "${FILE}";
        fi
    done
    

    Note that this is will probably be considered a "layman" solution by a professional. Maybe this is handled better by awk, which I am unfortunately not accustomed to using.