Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Remove files by date?

Status
Not open for further replies.

orjazmik

MIS
Oct 2, 2002
9
US
I'm looking to create a script that will allow me to remove files in a certain directory that are older than a certain date. What would be even cooler would be something where I could say that I want to remove everything more than a month old. Then I could just drop it in the cron and clean up the directory automatically. Any suggestions would be greatly appreciated. :) Thanks in advance.

- Marshall
 
Create a script containing:

#!/bin/ksh
DATADIR=/your/directory
find ${DATADIR} -type f -name "*filename*" -mtime +31 -exec rm -f {} \;

Create a line in the crontab :
00 12 1 * * * myscript > a_log_if_you_want 2>&1

HTH ;-) Dickie Bird

Honi soit qui mal y pense
 
That is awesome! That did exactly what I needed it to. Thanks so much for your help. :-D

- Marshall
 
Beware the find command is recursive
all sub-directories will be deal with the command
here the "exec rm -f {} " command is very dangerous
 
You can make find non recursive using:
Code:
cd $DATADIR
find . \( -type d ! -name . -prune \)     -o \( -type f -mtime +31 -exec rm -f {} \; \)
This should prevent the find from recursing into sub directories of $DATADIR. This only works if your version of find supports the prune directive.

Cheers, Neil

 
Fortunately, the directory I was cleaning out had no sub-directories. But this is definitely good to know for future reference. Thanks so much! :)

- Marshall
 
Hi:

I'm surprised nobody mentioned using xargs with find. It's been covered before in many threads. Check this one:

thread822-252908

Regards,

Ed
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top