Ubuntu – How to delete all first-level subfolders that do not have a specified string in their names

command linedeletedirectoryfilename

I know that there are quite a lot of answered questions about how to delete all files with or without a certain string in their names, as well as ones about how to delete all subfolders with a certain string in their names.

Yet, there are no questions regarding how to delete all subfolders without a certain string in there names.

So, as I have recently ran into such a problem, is there a quick command that will help with this situation? A bash script would be good enough, too.

EDIT:

By subfolders, I meant only the first-level subfolders, because I don't want to remove second-level or third-level subfolders, which might have names without the string, of first-level subfolders with the string.

Best Answer

Let us say you want to start find in the current directory, and restrict it to the first level of subdirectories:

find . -maxdepth 1

The find command has a useful flag -not (or !) which negates the following test. So in order to find a name which does not contain a substring, add

-not -name "*substring*"

IMPORTANT: you will want to exclude the current directory itself as well. Otherwise, the whole current directory would be deleted.

-not -name "."

Then you want to test for directories only:

-type d

And, if everything looks good, you want to delete these directories:

-exec rm -rf {} \;

which says "for all found directories, execute this command". The {} is a placeholder for the name of the directory (including the full path, so it works on the correct one). \; indicates the end of the command to be executed.

Summarizing:

find . -maxdepth 1 -not -name "*substring*" -not -name "." -type d -exec rm -rf {} \;

should work. But first, try it out without the -exec part.

Related Question