Coder Perfect

linux find regex


I’m having problems using the locate command’s regex. It’s probably something to do with command line escaping that I don’t understand.

Why aren’t they the same?

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

Bash, Ubuntu

Asked by Dijkstra

Solution #1

You should look into the -regextype parameter of find, which can be found in the 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:]]'

Answered by bmk

Solution #2

The default regular expression syntax used by find does not handle regular expressions with character classes (e.g. [[:digit:]]). To utilize them, you must specify a separate regex type, such as posix-extended.

Look through the Regular Expression documentation in GNU Find to see all of the regex types and what they support.

Answered by dogbane

Solution #3

It’s worth noting that -regex is path-dependent.

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

For what you’re doing, you don’t need to use -regex.

find . -iname "*[0-9]"

Answered by kurumi

Solution #4

You might try ‘.*[0-9]’ instead.

Answered by StKiller

Post is based on