Find and Regex – How to Use Regular Expressions for Finding Text

findregular expression

What am I doing wrong with this find expression?

; touch ook ooks
; find . -name 'ook' -or -name 'ooks' -type f
./ook
./ooks
; find . -name 'ook[s]?' -type f      
[returns nothing]
; echo $?
0

Best Answer

You're confusing regular expressions with shell search patterns.

? in shell means any single character.

? in regexp means the previous character (or sub-pattern) is optional.

Try:

find . -regex '.*ooks?' -type f

From the find man page:

       -regex pattern
              File  name  matches regular expression pattern.  This is a match
              on the whole path, not a search.  For example, to match  a  file
              named `./fubar3', you can use the regular expression `.*bar.' or
              `.*b.*3', but not `f.*r3'.  The regular  expressions  understood
              by  find  are by default Emacs Regular Expressions, but this can
              be changed with the -regextype option.
Related Question