Mac Terminal – How to Delete Files in a Directory That Match a Regexp

rmshellwildcards

How do I delete files in a directory that match a given regexp, or a similar solution, using a Mac terminal?

Best Answer

Use the find command.

Find all files (recursively) matching a regex: find . -type f -regex '/ex/'
Find all files (recursively) matching a regex and delete them: find . -type f -regex '/ex/' -exec rm {} \;

The brackets store the found pathname, and the backslash escapes the semicolon because it's passed to find; without escaping it, it would be consumed by the shell. If that went over your head, read the first two chapters of "Learning the Bash Shell".

Check the man pages for find for more options. There are a lot more ways to search.

Related Question