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 --
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 --
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 modtime
Tabpath
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