1754134 Members
3287 Online
108811 Solutions
New Discussion юеВ

delete old files

 
chakri
Occasional Contributor

delete old files

Hi,

is there any simple way to list files recursively in a directory and subdirectories and delete them.

i do not want to use find command as i dont know what to specify for -mtime.

Basic idea is if a file system is 100% i would need to delete files till it reaches 75% and i should delete oldest files in partition.

i tried the following.

1. ls -ltR -- doesnt give absolute parth
2. find . -name > list, then read the files from list and then do ls -l. this way i have absolute path, but now i'm not sure how to sort them based on date and time.

-C
3 REPLIES 3
James R. Ferguson
Acclaimed Contributor

Re: delete old files

Hi:

To find files recursively implies either using 'find' or rolling-your-own using Perl or C and with 'readdir()'.

Certainly I don't think you want to ignore the last modification time when choosing candidates for removal. After all, the largest file that will yield you significant space returns might be the most recent!

You could do:

# find /path -xdev -type f -mtime +7 -exec ls -l {} \+

...to see files that are older than 7-days since their last modification, or you could find and remove them with:

# find /path -xdev -type f -mtime +7 -exec rm {} \+

You might find it useful to present the list in descending size order:

# find /path -xdev -type f -mtime +7 -exec ls -l {} \+ | sort -k5,5 -nr

Regards!

...JRF...

Eric SAUBIGNAC
Honored Contributor

Re: delete old files

Bonjour,

"but now i'm not sure how to sort them based on date and time"

Here is a general guideline :

A first approach is to filter your "ls -l" with something like "sort -k 6M,6M -k 7n,7n"

6M : 6th field is a month
7n : 7th field is a number (day of month)

It will do the job correctly ONLY if files are less than 6 month old. The problem is that when a file is less than 6 month old, ls outputs time in the 8th field. If file is older ls outputs year in the 8th field ... Not good for sorting !

So you should do the job in 2 times.

First work with files older than 6 months with the command "find" then filter your "ls -l" with "sort -k 8n,8n 6M,6M -k 7n,7n". For the find I suggest to use the option "! -newer" rather than "-mtime". For example :

touch -t 200708220000 /tmp/flag
find . ! -newer /tmp/flag

Will find all files older than August 22th 2007 00h00.

Second work with files youger than 6 months with the command "find" then filter with "sort 6M,6M -k 7n,7n"

A beat complicated, but it should work


Eric
chakri
Occasional Contributor

Re: delete old files

thanks