josemigallas
josemigallas

Reputation: 3909

How to delete files based on the extension in MacOS terminal using regex?

I need to delete a huge amount of .zip and .apk files from my project's root folder I'd like to do it using the bash terminal (MacOS X).

So far I've successfully made it with two commands:

$ find . -name \*.zip -delete
$ find . -name \*.apk -delete

But I want to do it in one using regex:

$ find . -regex '\w*.(apk|zip)' -delete

But this regular expression doesn't seem to work because it's deleting anything... what am I doing wrong?

MORE INFO: An example of what I want to delete is android~1~1~sampleproject.zip.

Upvotes: 0

Views: 2199

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207425

I would use:

find . -type f \( -name "*.zip" -o -name "*.apk" \) -delete

Upvotes: 3

nu11p01n73R
nu11p01n73R

Reputation: 26667

$ find -E . -regex './[~a-zA-Z0-9]+\.(apk|zip)' -delete
  • The find tries to match the whole file name. So it is necessary to start the regex with ./

  • I believe find doesn't support \w \d etc. So replace them with character class. But find doesn't support them as well so you need to add -E to enable extended regular expressions.

    -E Interpret regular expressions followed by -regex and -iregex primaries as extended (modern) regular expres- sions rather than basic regular expressions (BRE's). The re_format(7) manual page fully describes both for- mats.


Example

For example consider the following commands

$ ls *.json
bower.json  composer.json   package.json

$ find -E . -regex "\./[a-zA-Z0-9]+\.(json)"
./bower.json
./composer.json
./package.json


Note The above answer is specifically for BSD find. If you are using GNU find, it won't support -E option, instead it support -regextype posix-extended. I can rewrite the above example as

$ find . -regextype posix-extended -regex "\./\w+\.(json)"

Upvotes: 3

Related Questions