Sunday, November 13, 2011

Delete oldest files in a directory

Often you need to process a list of file quickly.  This list can be from any number of sources, in this case I print a file list sorted by time , then delete the oldest ones cleaning out cruft that's accumulating on the server.


root@server:/var/spool/relay-ctrl/allow# ls -t | wc
   1527    1527   21806
root@server:/var/spool/relay-ctrl/allow# ls -t | tail -n 1450 | while read line ; do rm $line; done


so there was 1527  files lying around, and I remove the oldest 1450 of them.

I could just have as easily said keep the latest 100 by changing this to  tail -n +100



NAME
       tail - output the last part of files

SYNOPSIS
       tail [OPTION]... [FILE]...


  -n, --lines=N
              output the last N lines, instead of the last 10; or use +N to output lines starting with the Nth


Alternately  I could have used the fine command and removed any files over a certain age. 

WARNING, BE REALLY CAREFUL WITH STUFF LIKE THIS!!!
find /var/spool/relay-ctrl/allow  -mtime +30  -exec rm \{\} \;

Removes anything over 30 days old. 


No comments: