2

I want to find some dirs and delete all but the 10 latest dirs.

I can find . -maxdepth 1 -type d -name "XXX*" | xargs rm -rf but that would remove all of them.

I can't use head / tail because I don't know the length of the list. I thought of piping the result to wc -l and then doing subtracting 10 from it and then rm -rf'ing it, but I don't know how...

What I came up till now is this:

find . -maxdepth 1 -type d -name "XXX*" | # get the dirs list
wc -l | # count number
xargs -I{} expr {} - $(find . -maxdepth 1 -type d -name "XXX*") # send number to xargs and try to use expr to subtract from it the tail of the find

I'm stuck in the expr part and how to cut the list where I want

1 Answers1

4

Here you are:

find . -maxdepth 1 -type d -name "XXX*" -print0 | head -zn-10 | xargs -0 rm -rf

I have tested it, working fine. Note current directory "." also counts if -name "*"

From man head:

-n, --lines=[-]NUM
print the first NUM lines instead of the first 10; with the leading '-', print all but the last NUM lines of each file

dessert
  • 39,982
LeonidMew
  • 2,734
  • 1
  • 21
  • 38