Operating System - HP-UX
1834798 Members
2450 Online
110070 Solutions
New Discussion

Re: delete the 5 oldest files

 
SOLVED
Go to solution
Steve_3
Frequent Advisor

delete the 5 oldest files

I am looking for a script that will delete the 5 oldest files or "x" oldest files. Thanks.
8 REPLIES 8
Mel Burslan
Honored Contributor
Solution

Re: delete the 5 oldest files


count=5
cd /some/path
for file in `ls -1t | tail -${count}
do
rm ${file}
done


this will delete 5 oldest files. change count to your desired number
________________________________
UNIX because I majored in cryptology...
Mel Burslan
Honored Contributor

Re: delete the 5 oldest files


count=5
cd /some/path
for file in `ls -1t | tail -${count}`
do
rm ${file}
done


this will delete 5 oldest files. change count to your desired number
________________________________
UNIX because I majored in cryptology...
Mel Burslan
Honored Contributor

Re: delete the 5 oldest files

sorry for the double post. I realized I missed a backtick on the first post but obviously was not fast enough to catch it before it hit the server. Second answer's code part is the right one.
________________________________
UNIX because I majored in cryptology...
Pete Randall
Outstanding Contributor

Re: delete the 5 oldest files

It's pretty easy if there are no sub-directories mixed in with the files:

ls -lt . |tail -5 |awk '{ print $9 }' > /tmp/rm_list
for FILE in `cat /tmp/rm_list`
do
rm $FILE
done


Pete

Pete
Steve_3
Frequent Advisor

Re: delete the 5 oldest files

thanks. I will try it.
James R. Ferguson
Acclaimed Contributor

Re: delete the 5 oldest files

Hi Steve:

You don't need to create a temporary file that you read back and later delete, either:

# cd /path_to_stuff && ls -t|tail -5|xargs rm

Regards!

...JRF...
Steve_3
Frequent Advisor

Re: delete the 5 oldest files

thanks. great.
Arturo Galbiati
Esteemed Contributor

Re: delete the 5 oldest files

Hi
ls -tr|head -5|xargs rm -i

I put -i so system ask you before to delete files.
HTH,
Art