Mahshid Zeinaly
Mahshid Zeinaly

Reputation: 3978

find filename regular expression

I have a file called a_b

I use the following regular expressions to find it, and they work:

find . -iname "a_b"

find . -iname "a_*b"

But how come the below format does not find it?

find . -iname "a_{1}b"

Is not correct that {1} means the previous character which is "_" should match exactly one time ?

Upvotes: 1

Views: 110

Answers (1)

mklement0
mklement0

Reputation: 437418

You are using a regular expression, but find's -iname and -name actions expect patterns (globs).

Patterns (globs) (link courtesy of @Adam) are only distantly related to regular expressions and simpler, but also less powerful.

(As an aside: in your specific example, you need neither - just using the character as is will do.)

If you need the power of a regular expression and your find version supports it, use the -iregex or -regex actions (they're not part of the POSIX standard):

  • GNU find (Linux):

    find . -regextype posix-extended -iregex ".*/a_{1}b"
    
  • FreeBSD/OSX find:

    find -E . -iregex ".*/a_{1}b"
    

Note:

  • -iregex and -regex match the entire input path, hence the .*/ prefix.
    (By contrast, -iname and -name match only the filename part.)
  • Both snippets use options to explicitly activate support for extended regular expressions (-E / -regextype posix-extended) so as to ensure support for constructs such as {1} or to allow their use without needing to \- escape { and }.

Upvotes: 2

Related Questions