Delete all except latest datetime entery folder

Hello Expert,

I have a strange requirement,

I have folder where weekly backup are taken...
week1_bkup_02102011
week2_bkup_09102011
week3_bkup_16102011
.
.
everyweek a backup is created
I want to delete all folder except latest one

for example in above a week4_bkup_23102011 is added then it should remove all other three. only latest one should be present.

is there any logic then please help :confused:

Thanks

Assuming the modification time of the directories is reliable to sort out the latest:

set -- $(ls -t)
shift
rm -r $*

If the "latest" directory is last in the sorted output of directory names, you can do:

set -- $(ls -r)
shift
rm -r $*

If both are not reliable, you can use an appropriate sort command, like:

set -- $(ls | sort -t@ -k 0.16,0.19 -k 0.14,0.15 -k 0.12,0.13)
shift
rm -r $*
1 Like

thanks a lot for your response

Hope the below code will also help you.

add this code to your script or place it in cron. then every time this code runs, it will remove the file modified less than one day.

find \tmp -mtime -1 -exec rm -f {} \; 

Please change directory to your own.