Jerome
Jerome

Reputation: 6217

bash remove files less than string value

A cron action saves database files on an hourly basis and assigns a file name based on year, month, day and hour

/$(date +\%m)/$(date +\%y\%m\%d\%H)_thedb.sql

This leads to archive bloat and the goal is to keep the last file of the day (i.e. delete all those lesser than 15050923* ) in a separate cron action.

What is an effective way of achieving this?

Upvotes: 0

Views: 55

Answers (1)

chw21
chw21

Reputation: 8140

Before you start with complex bash string substitutions, I suggest you try to go after the file date. find can help you with that.

For example, to delete all files in a directory that are older than 5 days, you could try something like this:

find <DIR> -mtime +5 -exec rm {} \;

Now if there are subdirectories in <DIR>, you might also want to include the options -type f to limit the finding to files, and -maxdepth 1 to not search subdirectories.

If you have a file and want to delete everything older than that, you could slightly modify this:

find <DIR> -not -newer <FILE> -not -name <FILE> -exec rm {} \;

I simply don't know why there is no -older search term in find, it seems so obvious.

Warning: I strongly recommend to first leave out -exec and everything after it to check whether the files it finds can all be deleted.

Upvotes: 1

Related Questions