Using find in macOS terminal with regex

13,012

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'
Share:
13,012

Related videos on Youtube

minttoothpick
Author by

minttoothpick

Updated on September 18, 2022

Comments

  • minttoothpick
    minttoothpick over 1 year

    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!

    • John1024
      John1024 about 6 years
      -name matches globs not regexes. If you want to match regexes, use -regex. (And, if you don't like the default regex type, use -regextype.)
  • tripleee
    tripleee about 6 years
    The final regex lacks a backslash before the literal dot and a closing quote at the end of the regex. My High Sierra MacOS (which is basically BSD) does not like the . before the -E option but reversing their order fixes that.