3

I'm trying to use find with the regex option. However my regular expression only captures the basename of the file. Is there a reference to the "directory find is currently in" I can use in my regular expression so that I don't have to account for it by means of a leading .*?

(I'm looking for something like the $File::Find::dir in perl's File::Find module.)

As an example: suppose I want to find all files matching the regular expression baz\d anywhere below /foo/bar/. Using find /foo/bar -regex 'baz\d' won't find a file named baz1 at /foo/bar/ because the pattern baz\d doesn't match the full filename /foo/bar/baz1, so instead I'm using find /foo/bar -regex '.*baz\d' which works, but I'm wondering whether I can replace that .* with something more robust?

  • Is this in shell scripting? And can you post the lines you're using now and some example of what you would try to accomplish? The example should make it more clear. – gertvdijk Dec 4 '12 at 20:34
  • @gertvdijk: do you know of another category using find may fall under? – Isaac Kleinman Dec 4 '12 at 20:57
3

You can "anchor" the beginning of the filename by including a slash in the regex pattern:

find /foo/bar/ -regex '.*/baz\d'

This will ensure that you only get files like baz1, and not bazbaz1.

  • I guess that's the best we can do. – Isaac Kleinman Dec 5 '12 at 16:20

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.