-1

To delete all the directories inside a folder except the last 4 modified folders in Linux, does the below command work?

find /path/folder -mindepth 1 -maxdepth 1 -type d | xargs ls -td -- | tail -n +5 | xargs -r rm -r --
jarvis
  • 11
  • 4
  • 1
    What is the point of `find` there? `ls -td ./*/` does the same thing. – oguz ismail Sep 05 '22 at 12:24
  • Does this answer your question? [Delete all but the most recent X files in bash](https://stackoverflow.com/questions/25785/delete-all-but-the-most-recent-x-files-in-bash) – tink Sep 05 '22 at 17:59

1 Answers1

2

The following GNU solution is a little overkill but it's robust.

GNU find has a -printf predicate that allows to prepend the modification time to the outputted paths. You can then sort those modtimeTabpath entries, drop the first four & strip the modification time with sed, and then rm the remaining ones.

find . -type d -mindepth 1 -maxdepth 1 -printf '%Ts\t%p\0' |
sort -zr -k1,1 |
sed -z '1,4d; s/^[^\t]*\t//' |
xargs -0 rm -r
Fravadona
  • 13,917
  • 1
  • 23
  • 35