How to Delete Files with a Specific Extension in all Subdirectories Recursively

I was trying to recursively delete all my *.css files recently because I accidentally ran a SASS to CSS compiler, which bloated my repository.

I tried using rm -r, since I knew the -r flag recursively traversed the directory tree, but it has no functionality to match regex patterns for files (only directories).

-r, -R, --recursive
removes directories and their contents recursively

In order to recursively delete files, we want to use find.

find . -type f -name '*.css' -delete

We are searching for all files (-type f) in the current and child directories (find .) that match the given pattern (*.css).

Then we’re delete those files (-delete).

find . -type f -name '*.css' -exec rm {} +

Here, we’re doing the same search, but instead of using -delete, we’re running -exec rm {} +.

The curly braces {} is a placeholder for the file names and paths.

The plus sign + allows us to handle multiple files simultaneously.