Delete all files / folders in subdirectories with a certain pattern on terminal

Today I had a problem on terminal. I have such a folder structure:

./<level_A>/<level_B>_good

or

./<level_A>/<level_B>_bad

Thus I have some folders(level_A) and in each folder there are another level of folders(level_B). On level_B, there are “good” folders and “bad” folders. “Good” folders end with “_good” and “bad” folders end with “_bad”. Also, there are files in all level_B folders.

For example, a good folder can be

./folder_A_1/folder_a_good

and a bad folder can be in the same directory on level A

./folder_A_1/folder_b_bad

Normally, when we want to delete a group of folders that ends with a particular name, we just use

rm -r *_bad

However, this approach does not apply here because I have too many folders on level_A. If I use the rm command, I have to enter and exit all the folders such as

cd folder_A_1

rm -r *_bad

cd ../folder_A_2

rm -r *_bad

...

I have too many folders on level A: folder_A_1 up to folder_A_1000. Hence, I can not use this common approach.

Then I thought of another command I have used: find. That command lists everything in the directory recursively so it is able to target the folders in the subdirectories. That is good. However, how to find, filter and delete? That means, find all the folders recursively, select those paths ending with “_bad”, and delete them. Fortunately, by looking at the manual of find, it turns out that we have a very nice option -delete. Thus we can find all the directories ending with “_bad” using this command

find . -type d -name "*_bad"

-type d requires the target to be a directory. -name “*_bad” specifies the pattern of the name. By this, we find and filtered to target all the directories and subdirectories that ends with “_bad”.

Next, we will make use of the command -delete. 

find . -type d -name "*_bad" -delete

That deleted all the “bad” subdirectories for me and solved my problem. Yay!

I think this can be generalized as a way to simplify processing the system files on terminal. Usually, when it comes to complicated group processing, we have to write bash scripts. However, if we can make good use of the built-in commands, that can save our time.

Leave a Reply

Your email address will not be published. Required fields are marked *