Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to delete all files except the latest three in a folder

Tags:

unix

I have a folder which contains some subversion revision checkouts (these are checked out when running a capistrano deployment recipe).

what I want to do really is that to keep the latest 3 revisions which the capistrano script checkouts and delete other ones, so for this I am planning to run some command on the terminal using a run command, actually capistrano hasn't got anything to do here, but a unix command.

I was trying to run a command to get a list of files except the lastest three and delete the rest, I could get the list of files using the following command.

(ls -t /var/path/to/folder |head -n 3; ls /var/path/to/folder)|sort|uniq -u|xargs

now if I add a rm -Rf to the end of this command it returns me with file not found to delete. so thats obvious because this returns only the name of the folder, not the full path to the folder.

is there anyway to delete these files / folders using one unix command?

like image 497
nivanka Avatar asked Dec 15 '10 06:12

nivanka


1 Answers

Below is a useful way of doing the task.......!!

for Linux and HP-UX:

ls -t1 | tail -n +50 | xargs rm -r # to leave latest 50 files/directories.

for SunOS:

rm `(ls -t |head -n 100; ls)|sort|uniq -u`

like image 50
Mubasheer Ahmed Avatar answered Oct 13 '22 14:10

Mubasheer Ahmed