Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have the following files, and need to match them like:

./       -match

./qux/   -match

./            -match

./            -no match

./foo.bar3          -no match

I have tried:

find . -regex ".*foo(bar[0-9])?.sh"

but it returns nothing. I cannot figure out why that regex won't work... help please?

share|improve this question
up vote 2 down vote accepted

Your regular expression has two errors:

  1. It misses a (literal) dot after foo.

  2. find requires you to escape the parentheses when not used as literal parentheses.

Also, you should escape the dot before sh, since it will match any character.

The fixed command now reads:

find . -regex ".*foo\(\.bar[0-9]\)?\.sh"

Error 2., by the way, is the reason why I don't like find's -regex switch: Inconsistent escaping.

It works, of course, but grep -P uses Perl Compatible Regular Expressions (PCRE), so there are more features, but less surprises and pitfalls.

Personally, I'd use:

find . | grep -P "foo(\.bar\d)?\.sh"
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .