-2

I want to delete directories that are five days old, based on the directory name, instead of unix timestamp. Let us assume that directories are created like test_2013-05-20-12:23:43 and so on.

I want to delete all directories that are 5 days older, i.e before the 16th.

Is this possible to do?

Randy Howard
  • 2,165
  • 16
  • 26
RAVITEJA SATYAVADA
  • 2,503
  • 23
  • 56
  • 88

3 Answers3

0

If you are not specific with file name criteria use this

find /path/to/files* -mtime +5 -exec rm {} \;

Note that there are spaces between rm, {}, and \;

Explanation

The first argument is the path to the files. This can be a path, a directory, or a wildcard as in the example above. I would recommend using the full path, and make sure that you run the command without the exec rm to make sure you are getting the right results. The second argument, -mtime, is used to specify the number of days old that the file is. If you enter +5, it will find files older than 5 days. The third argument, -exec, allows you to pass in a command such as rm. The {} \; at the end is required to end the command.

read this Link for more info

Zigma
  • 529
  • 6
  • 37
0

It's a little tricky, first of all find out the unix epoch of 5 days ago

$ date --date='5 days ago' +%s
1368599762

and then you can parse each directory name, extract the time part, transform it in a unix epoch time and compare if are before that date; if yes delete it.

gipi
  • 2,432
  • 22
  • 25
0

If the filenames are using ISO-8601 formatting as in your example, it's fairly easy to just do a lexical comparison:

oldest=`date -d 'today -5 days' '+test_%F-%T'`
find "$log_dir" -name 'test_*' -print \
  | while read f; do test "$f" '>=' "$oldest" || rm "$f"; done

(untested; assumes filenames don't include newlines)

This is a great fringe-benefit of standardizing on ISO-8601. :-)

Toby Speight
  • 27,591
  • 48
  • 66
  • 103