Friday, 17 May 2013

How to delete all files in a directory except the last 3 files ?

The trick here is as follows
1) Do the listing sorted by file modification time.
2) Use tail or head to cut out the 3 latest files and
3) Then do ’ rm’ on all files that remain.

Suppose you have to delete all files except the latest 3 from the folder /var/path_to_folder.
So the below command will accomplish your task.

# cd /var/path_to_folder && /usr/xpg4/bin/ls -t /var/path_to_folder | tail -n +3 | xargs rm –r


The above command lists all files in the directory sorted as per last modification time ( you may use –u switch to ls command to sort according to last access time instead of last modification time, see man page for ls for details), then tail command takes the listing as its input and cuts out the 3 files from top. Pay attention to the + sign before 3 , if i had used -3 in place +3 the result would have been something entirely different. The –n +3 operates on top of the listed output and removes the top 3 lines from the output. On the other hand , -n -3 would have operated on last 3 lines of the output and instead of removing those lines it would have printed out those lines to the terminal. The meanings and usage of + and - are very different. The usage also changes dramatically if i had used head instead of tail to cut out the 3 lines. Take care of this and before going on to our next step with "xargs and rm" command, be sure of the output you are getting here , as you would end up deleting last 3 files accidently if you misinterpreted the above.

Why i used xargs ? Because xargs constructs argument list and invokes the desired utility ( in our case ‘rm’ ) sequentially on each argument from the list. Our output after doing the tail is a list of files, one per line , as is usual when doing listing. The "rm" command wont act on these one per line arguments if supplied as it is to a single rm invocation. So xargs helps us here by invoking rm once for each filename.

No comments:

Post a Comment