8

suppose I have two files: ac and abc. I want to find a regex to match both files. Normally I would expect the following regex to work, but it never does:

find ./ -name ab?c

I have tried escaping or not the questionmark, this never seems to work. Normally in the regex documentations I have found; ? means: previous character repeated 0 or 1 times, but find doesn't seem to understand this.

I have tried this on two different find versions: GNU find version 4.2.31 and find (GNU findutils) 4.6.0

PS: this works with *, but I specifically would like to match just one optional character.

find ./ -name a*c

gives

./ac
./abc

4 Answers 4

11

The expression passed to -name is not a regex, it is a glob expression. A (single) glob expression can't be used for your use case but you can use regular expressions using -regex:

find -regex '.*/ab?c'

Btw, the default regular expression language is Emacs Style as explained here : https://www.emacswiki.org/emacs/RegularExpression . You can change the regex language using -regextype.

6

To match the expression with only one optional character try using or option:

touch abc ac abbc
find . -name "a?c" -or -name "ac"

Gives you only: abc and ac names.

Generally you can build pretty complex find queries using or and and options =)

3

The find -name option uses a glob pattern, which is not the same as a regex. For globs, ? means any single character. If you want a character to be optional, you need to use two patterns:

find ./ -name abc -o -name ac
1

Other answers are good enough to have a solution but knowing find's -regex option matches on whole entry is essential. So you can't just do a partial match:

-regex 'ab?c'

You have to use one or two dot-stars:

-regex '.*ab?c.*'

Also without wildcards this would be possible using grep:

ls . | grep 'ab\?c' 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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