• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 936
  • Last Modified:

CentOS Delete Files

Using the command line in CentOS how do i delete all files within a specific directory that have a last modified date older than June 1, 2012?
3 Solutions
touch -t 201206010000 /tmp/from
find /specific/directory -type f  ! -newer /tmp/from | xargs rm
rm /tmp/from

The above will recurse into subdirectories of /specific/directory.
If this is not desired add "-maxdepth 1" to the arguments to "find":

touch -t 201206010000 /tmp/from
find /specific/directory -maxdepth 1 -type f  ! -newer /tmp/from | xargs rm
rm /tmp/from
using the -mtime +90 is another option, but this will adjust unlike the WMP example based on the date that you run it. -mtime +90 means a file older than 90 days
Switching -mtime -90 will mean less than 90 days old.
This should help:

cd /path/to/your/folder; find -type f -mtime +`echo $(( ( $(date +%s) - $(date -d "06/01/2012" +%s) ) /(24 * 60 * 60 ) ))` -print;

Open in new window

I included the print so that you will be able to see what files are going to be deleted. When you have verified that they are the files that you actually want to delete you can change the print to delete and it will remove the files. Here a couple alternatives if you, like me, are a careful administrator/user who wants to be sure they are deleting the right files:

This will tell you what files you are actually going to delete and their current modified dates, before you actually delete them (the head -20 means it will only list the first 20 files, you just need a few to verify the dates):

cd /path/to/your/folder; find -type f -mtime +`echo $(( ( $(date +%s) - $(date -d "06/01/2012" +%s) ) /(24 * 60 * 60 ) ))` -exec ls -lh {} \; 2> /dev/null | head -20

Open in new window

You can also change the actually date you see in this one-liner in case you need to reuse it to delete some other files as you are doing here, i.e. $(date -d >>>"06/01/2012"<<< +%s)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now