Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

./foo.bar1.sh       -match

./qux/foo.bar2.sh   -match

./foo.sh            -match

./baz.sh            -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
add comment

1 Answer

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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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