Tuesday, March 15, 2022

[SOLVED] Delete all directories that contain digit(s) except for the most recently created in Red Hat Linux Server using Regex

Issue

File Structure:

/56
/57
/58
/lastFailedBuild
/lastStableBuild
...

I'm trying to delete only /56 and /57.

Here is my current shell script that gets run during my Jenkins process.

rm -rf [0-9]*

but that obviously also deletes /58. I would like to do something like this: rm -rf [0-9]*!({env.BUILD_NUMBER}) where I'm able to keep the rest of the directories including /58.


Solution

You may get a list of directories without the last one using head -n -1:

rm -rf `ls -d [0-9]* | head -n -1`

On the platforms where head -n -1 is not available, sed '$ d' may be used instead (credits to @l'L'l):

rm -rf `ls -d [0-9]* | sed '$ d'`


Answered By - Dmitry Egorov
Answer Checked By - Terry (WPSolving Volunteer)