Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all but the 4 newest directories

Tags:

bash

shell

I want to delete all but the 4 newest directories in my parent directory. How would you do this in Bash?

like image 429
eventi Avatar asked Dec 22 '22 14:12

eventi


2 Answers

ls -atrd */ | head --lines=-4 | xargs rm -rf

Edit: added 'a' argument to ls

like image 74
Leigh Caldwell Avatar answered Jan 08 '23 09:01

Leigh Caldwell


Please clarify if you mean “delete all directories but the four newst ones” or “delete everything (files and directories) except for the four newest directories”.

Please also note that creation times are not known for directories. One can only tell when a directory was last modified, that is, had files added, removed or renamed.

like image 43
Alexey Feldgendler Avatar answered Jan 08 '23 09:01

Alexey Feldgendler