2

I have two folders, CA01 and CA02 under current folder, foo:

foo -+
     |
     +-CA01
     |
     +-CA02

When I type

find . -regex ".*CA[0-9]+" -exec echo {} +

Or

find . -regex ".*CA[0-9][0-9]" -exec echo {} +

I have the following output, which is expected:

./CA01 ./CA02

But when I type in

find . -regex ".*CA[0-9]\{2\}" -exec echo {} +

Nothing shows up, which is quite unexpected.

Because, by default, find uses emacs regex. I could use all the above to match the two folders.

Am I missing something here?

2

You need to change the -regextype to one that supports repetition counts (i.e. {2}). The default one, emacs doesn't appear to support the counts. The default regex type imitates an older version of Emacs that didn't have a syntax for repetition counts. The types below appear to work for me.

Examples

posix-egrep

$ find foo -regextype posix-egrep -regex ".*CA[0-9]{2}" -exec echo {} +
foo/CA02 foo/CA01

sed

$ find foo -regextype sed -regex ".*CA[0-9]\{2\}" -exec echo {} +
foo/CA02 foo/CA01

posix-extended

$ find foo -regextype posix-extended -regex ".*CA[0-9]{2}" -exec echo {} +
foo/CA02 foo/CA01

There are others but I didn't try any more. See the find man page and search for -regextype.

excerpt

-regextype type
       Changes  the  regular  expression  syntax  understood by -regex and 
       -iregex tests which occur later on the command line.  Currently
       implemented types are emacs (this is the default), posix-awk, 
       posix-basic, posix-egrep and posix-extended.

My version of find

$ find -version
find (GNU findutils) 4.5.9
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Eric B. Decker, James Youngman, and Kevin Dalley.
Built using GNU gnulib version 1778ee9e7d0e150a37db66a0e51c1a56755aab4f
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION FTS(FTS_CWDFD) CBO(level=2) 
  • It seems true that the default does not support the count. BTW, did you update your find manually? My find version is only `4.4.2' on ubuntu 13.04. – gongzhitaao Oct 2 '13 at 3:19
  • @gongzhitaao - I'm on Fedora 14. That's the version that's stock with it. – slm Oct 2 '13 at 3:25
  • 1
    A little gotcha that might trip some people up: the -regextype switch must be entered /before/ the -regex one, or else it won't take effect. – Dologan Apr 16 '15 at 17:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.