Finding / deleting old files

I just wanted to clean up my Maven repository a bit and remove some old artifacts. This is unproblematic since all missing artifacts would be fetched again. But then the question arised: How can I find files that are older then a specific date? Unfortunately the Finder does not have an appropriate search function, nor Spotlight helps. Yes, there is the find command, but it only has a -newer option, no -older.

In my search I found this forum post, which gave me the solution. The solution is to create a temporary file with the touch command and give it the timestamp you want to compare with. Then use the find command and invert the query with “!”.

Let’s say we want to find all files older then 2008-01-01 from the current directoy “./” and below. The result will be stored in a temp file that is used as input for the tar command to archive the old files. The result can be queried like this:

touch -t 200801010000 /tmp/touchfile
find ./ ! -newer /tmp/touchfile > /tmp/filelist
tar --create --gzip --files-from /tmp/filelist --file repository-before-2008.tar.gz
rm /tmp/touchfile
rm /tmp/filelist

Maybe you want to use a date relative to the current date instead of a fixed date. This can be achieved by evaluating the date command in combination with touch. For an example, to modify the timestamp file’s modification date 6 months back, use

touch -t $(date -v -6m "+%Y%m%d%H%M") /tmp/filelist

With the zip command the older files can be archived in one command:

zip -rttq 2008-01-01 repository-before-2008 ./

In my case the tar (and also tar.gz) archive was by far larger then the zip archive. I did not investigate the reason further yet.

After creating the backup zip I used the find command again to delete the old files from the repository.

find ./ ! -newer /tmp/touchfile -delete
Advertisements