Filtering Filenames with bash Filtering Filenames with bash bash bash

Filtering Filenames with bash


The following script expects GNU date to be installed. You can call it in the directory with your log files with the first parameter as the number of months.

#!/bin/shmin_date=$(date -d "$1 months ago" "+%Y%m%d")for log in *.log.*;do        [ "${log%.log.old}"     "!=" "$log" ] && continue        [ "${log%.*}.$min_date" "<"  "$log" ] && continue        cat "$log" >> "${log%.*}.old"        rm "$log"done


Presumably as a log file, it won't have been modified since it was created?

Have you considered something like this...

find ./ -name "*.log.*" -mtime +60 -exec rm {} \;

to delete files that have not been modified for 60 days. If the files have been modified more recently then this is no good of course.


You'll have to compare the logfile date with the current date. Start with the year, multiply by 12 to get the difference in months. Do the same with months, and add them together. This gives you the age of the file in months (according to the file name).

For each filename, you can use an AWK filter to extract the year:

awk -F. '{ print substr($3,0,4) }'

You also need the current year:

date "+%Y"

To calculate the difference:

$(( current_year - file_year ))

Similarly for months.