Macos – Using find in macOS terminal with regex

findmacosregexterminal

I'm trying to search a folder containing variations on different image filenames:

1_2-300x224.jpg
1_2-600x449.jpg
1_2-600x600.jpg
1_2-768x575.jpg
1_2-802x600.jpg
1_2.jpg

The plan is to find and delete the files ending in 2-4 digits + 'x' + 2-4 digits. I can create this match on Regexr using the expression .*(\d{2,4}x\d{2,4}).jpg (this expression highlights everything except for 1_2.jpg).

However, running find . -name ".*(\d{2,4}x\d{2,4}).jpg" returns no results.

I'm flummoxed!

Best Answer

There are a couple of issues here. Firstly, as John mentioned, -name does sub-string matching with globs, you need to use -regex, and secondly, there are regular expression dialect incompatibilities. By default GNU find uses Emacs regular expressions and BSD find uses posix-basic regular expressions. If you have find.info installed you can read more about it here:

info find.info 'Reference' 'Regular Expressions' 'emacs regular expression'

Supported regular expression dialects can be found here:

info find.info 'Reference' 'Regular Expressions'

Here:

* findutils-default regular expression syntax::
* emacs regular expression syntax::
* gnu-awk regular expression syntax::
* grep regular expression syntax::
* posix-awk regular expression syntax::
* awk regular expression syntax::
* posix-basic regular expression syntax::
* posix-egrep regular expression syntax::
* egrep regular expression syntax::
* posix-extended regular expression syntax::

GNU find

You can make your expression work with posix-extended like this with GNU find:

find . -regextype posix-extended -regex '.*[0-9]{2,4}x[0-9]{2,4}.jpg'

Output:

./1_2-600x600.jpg
./1_2-802x600.jpg
./1_2-600x449.jpg
./1_2-300x224.jpg
./1_2-768x575.jpg

BSD find

I don't have access to BSD find, but I think this should work:

find -E . -regex '.*[0-9]{2,4}x[0-9]{2,4}\.jpg'
Related Question