Wednesday, June 10, 2009

Purge old files on Linux/Unix using “find” command

I've noticed that one of our interface directories has a lot of old files, some of them were more than a year old. I checked it with our implementers and it turns out that we can delete all files that are older than 60 days.

I decided to write a (tiny) shell script to purge all files older than 60 days and schedule it with crontab, this way I won't deal with it manually. I wrote a find command to identify and delete those files. I started with the following command:

find /interfaces/inbound -mtime +60 -type f -maxdepth 1 -exec rm {} \;

It finds and deletes all files in directory /interface/inbound that are older than 60 days.
"-maxdepth 1" -> find files in current directory only. Don't look for files in sub directories.

After packing it in a shell script I got a request to delete "csv" files only. No problem... I added the "-name" to the find command:

find /interfaces/inbound -name "*.csv" -mtime +60 -type f -maxdepth 1 -exec rm {} \;

All csv files in /interface/inbound that are older than 60 days will be deleted.

But then, the request had changed, and I was asked to delete "*.xls" files further to "*.csv" files. At this point things went complicated for me since I'm not a shell script expert...

I tried several things, like add another "-name" to the find command:

find /interfaces/inbound -name "*.csv" -name "*.xls" -mtime +60 -type f -maxdepth 1 -exec rm {} \;

But no file was deleted. Couple of moments later I understood that I'm trying to find csv files which is also xls files... (logically incorrect of course).

After struggling a liitle with the find command, I managed to make it works:

find /interfaces/inbound \( -name "*.csv" -o -name "*.xls" \) -mtime +60 -type f -maxdepth 1 -exec rm {} \;

:-)

Aviad

7 comments:

Rutuja Deshmukh said...

Hi,
You havedone really fablous blog. I found your blog very interesting and very informative for Oracle. I think your blog is great information source & I like your way of writing and explaining the topics.i found the other related to this.
Regards
oracle fussion middleware

Rutuja Deshmukh said...

Hi
You have a fabulous blog.I felt your blog very interesting and very informative for Oracle Applications. I think your blog is great information source & I like your way of writing and explaining the topics.i found other too
regards
oracle fussion middleware

Oracle User List said...

Nice commands on Linux/Unix.

Facebook Application Developer said...

i want to know that what is difference between LINUX AND UNIX ?
are they help full in any app development ?

vijay @ unix commands said...

can you please tell how to convert excel into csv file in unix os.

Thanks,
Vijay
find command

Path Infotech said...

Thanks for sharing the information

Oracle Certification Program

Jags said...

Nice article about JRE upgrade

I have been trying the upgrade in my EBS env. It is really simple but some user may face issue