I'd like to write a script that delete all the directories (that are not empty) from a directory, but keep the most recent one. Is that possible, and how?
02 Answers
Here is a way to do this using find.
find -type d ! -wholename $(find -type d -printf '%T+ %p\n' | sort -r | head -1 | cut -d" " -f2) ! -wholename "." -exec rm -r {} +Command breakdown:
find -type dthe first part tells find to search for directories only! -wholenameexclude hits with the following complete name. The following part (between$()) is evaluated and used as file name here$(find -type d -printf '%T+ %p\n' |print timestamps for directoriessort -r |sort them newest to oldesthead -1 |take only the first line (newest directory)cut -d" " -f2)remove the timestamp from the output
! -wholename "."exclude hits with the complete name.. You cannot remove the directory, your currently working in.-exec rm -r {} +remove the matching files.
You should run the command without the last part (-exec rm -r {} +) first, to see which directories will be removed.
Example:
directory content:
Aug 4 14:38 bar/
Aug 4 14:38 bla
Aug 4 14:38 foo/
Aug 4 14:41 foobar/running command:
find -type d ! -wholename $(find -type d -printf '%T+ %p\n' | sort -r | head -1 | cut -d" " -f2) ! -wholename "." -exec rm -r {} +resulting directory content:
Aug 4 14:38 bla
Aug 4 14:41 foobar/note that bla is a file and not a directory. So it will not be removed.
I found an answer, and leave it here, it might be useful for other users :
cd /path/to
rm -r `ls -t | awk 'NR>1'` 1