0

I have a path where there will be build directories copied, so i need to keep only latest 3 directories and delete others, not by date but with the latest build number.

If i have the following directories in the path /tmp

1.1.0000-021, 1.1.0000-005, 1.1.0000-018, 1.1.0000-004

I should be deleting 1.1.0000-004 directory in /tmp path as its the oldest directory.

I was trying with rm -rf /base/path -type d -ctime 4 , but this is based on latest file, not sure about getting oldest number to delete.

2
  • You do this with a script. What have you tried and where does it fail? This is not a "write my code for me" site.
    – Jan Doggen
    Sep 11, 2014 at 10:02
  • "...and where does it fail"? And edit your question. All the relevant information should be in there, don't answer in comments.
    – Jan Doggen
    Sep 11, 2014 at 10:10

1 Answer 1

0

You could use the following chain:

ls: list files/directories

sort -nr: sort files/directories numerical, reversed

tail: leave from the list just the last $n (here:4) entries (if only 4 remain, the list will be empty)

for example:

ls | sort -nr | tail +5 

Then take the files and delete them; (i.e. with xargs + rm)

2
  • 1
    Thanks Philip, this seems working ls |sort -nr |tail -n +4 |xargs rm -rf
    – guest
    Sep 11, 2014 at 13:32
  • Glad i could help!
    – derphilipp
    Sep 13, 2014 at 18:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .