the find utility is powerful, but I'd need some additional features.

its -regex search treats each filename (or dirname) as a string and applys given regex only at the beginning of name. like python's re.match(..). if it doesn't produce a match, it won't be found.

for example If i want to find files containing 'log', (I know there are simpler ways to find files whose filename contains 'log' without regex, but it's only for an example)

$ find -regex 'log'

$ find -regex '\./.*log.*$'

so, is there a way to make find with -regex that uses regex on filenames, like grep or python's re.search(..) - not only at the start of a string, but anywhere where it can match?


The regex is not only applied to the beginning, it is applied to the whole string. You just need to give the right regex, one that captures the entire file name:

$ ls -l
total 0
-rw-r--r-- 1 terdon terdon 0 Oct  6 15:46 aaafoo
-rw-r--r-- 1 terdon terdon 0 Oct  6 15:46 aaafooaaa
-rw-r--r-- 1 terdon terdon 0 Oct  6 15:46 fooaaa
$ find . -regex ".*foo.*"  
$ find . -regex "^./foo.*"  
$ find . -regex ".*foo"

You might be looking for the -name test, which takes globs, not regular expressions:

$ find  . -name "*foo*" 
  • thanks, but your example clearly indicates that all the regex is applied only to beginning(and that produces a match, because of .* or ^./ at the beginning of regexes, which would be unnecessary if the regexs are not only tried at the beginning of a string.) -name is only for globs.. so, guess the only solution is me writing more longer regexes. – thkang Oct 6 '13 at 14:09
  • 1
    @thkang what I'm saying is that the regex needs to describe the entire string from the beginning to the end. It is not only matched against the beginning it's matched against the entire thing. There is no file name you cannot describe that way. Simply adding a .* allows you to match anywhere within the string. I can't think of any example of a file name that I could not write a regex for. – terdon Oct 6 '13 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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