75

I'm having trouble using the regex of the find command. Probably something I don't understand about escaping on the command line.

Why are these not the same?

find -regex '.*[1234567890]'
find -regex '.*[[:digit:]]'

Bash, Ubuntu

Dijkstra
  • 2,490
  • 3
  • 21
  • 35

4 Answers4

72

You should have a look on the -regextype argument of find, see manpage:

      -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. 

I guess the emacs type doesn't support the [[:digit:]] construct. I tried it with posix-extended and it worked as expected:

find -regextype posix-extended -regex '.*[1234567890]'
find -regextype posix-extended -regex '.*[[:digit:]]'
bmk
  • 13,849
  • 5
  • 37
  • 46
  • 2
    I thought it might be that, but I checked the emacs regex definitions and they appear to support [:digit:]. http://www.gnu.org/software/emacs/manual/html_node/elisp/Char-Classes.html#Char-Classes – Dijkstra Apr 12 '11 at 13:19
57

Regular expressions with character classes (e.g. [[:digit:]]) are not supported in the default regular expression syntax used by find. You need to specify a different regex type such as posix-extended in order to use them.

Take a look at GNU Find's Regular Expression documentation which shows you all the regex types and what they support.

dogbane
  • 266,786
  • 75
  • 396
  • 414
  • 1
    Thanks. That document is the one I should have been looking for. All I could find was http://www.gnu.org/software/emacs/manual/html_node/elisp/Char-Classes.html#Char-Classes - which seemed to suggest that character classes *were* supported in "emacs regex mode". – Dijkstra Apr 12 '11 at 13:24
  • 1
    Also check [Regular_expression#Character_classes](http://en.wikipedia.org/wiki/Regular_expression#Character_classes) - very helpful resource – asoundmove Jul 23 '13 at 15:48
30

Note that -regex depends on whole path.

 -regex pattern
              File name matches regular expression pattern.  
              This is a match on the whole path, not a search.

You don't actually have to use -regex for what you are doing.

find . -iname "*[0-9]"
yegor256
  • 102,010
  • 123
  • 446
  • 597
kurumi
  • 25,121
  • 5
  • 44
  • 52
1

Well, you may try this '.*[0-9]'

StKiller
  • 7,631
  • 10
  • 43
  • 56