0

I have a folder with folders inside of them, named 1.1, 1.2, 1.3 ... 1.30.

I want to delete all folders except the last 10 versions

So delete all folders except 1.20, 1.21, 1.22, 1.23, 1.24, 1.25, 12.26, 1.27, 1.28, 1.29, 1.30

I also want to make sure that if there are 10 or fewer then none get deleted

Somthing like works but it wont preserve the last 10 versions

ls | sort -v | head -n +10 | xargs -I {} rm -- {}

How can I do this?

user1070953
  • 113
  • 2

3 Answers3

0

You could loop over the files and keep a counter. It's not a one-liner, but it should work for you.

i=0
preserve_n=10
while read -r dir; do
    [ "$i" -ge "$preserve_n" ] && rm -rf "$dir"
    i=$((i + 1))
done < <(find . -maxdepth 1 -mindepth 1 -type d | sort -r -V)
John Moon
  • 924
  • 6
  • 10
0

To preserve 10 directories (or fewer) and assuming GNU tools are available, you could us this null-terminated pipeline if there are no other files in this directory:

printf '%s\0' * | sort -zVr | tail -zn+11 | xargs -r0 rm -r -- 
Freddy
  • 4,548
  • 1
  • 7
  • 17
0

Here is one way:

$ for n in {01..30}; do mkdir "1.$n"; done
$ find . -mindepth 1 -type d -print0 | while IFS= read -r -d '' dir; do if (( 10#${dir##*.} < 20 )); then rmdir $dir; fi; done
$ ls -1
1.20
1.21
1.22
1.23
1.24
1.25
1.26
1.27
1.28
1.29
1.30
htaccess
  • 2,800
  • 26
  • 31