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.

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'
(nothing)

$ find -regex '\./.*log.*$'
./log9
./log7
./log5
./log0
./log2
./log4
./log6
./log8
./log3
./log1

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?

share|improve this question

1 Answer 1

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.*"  
./aaafoo
./aaafooaaa
./fooaaa
$ find . -regex "^./foo.*"  
./fooaaa
$ find . -regex ".*foo"
./aaafoo

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

$ find  . -name "*foo*" 
./aaafoo
./aaafooaaa
./fooaaa
share|improve this answer
    
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

 
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.