6

I'm having some issues dealing with the find command; I don't know the syntax for it very well and I need to use it in a script to find a specific directory structure that could be located anywhere.

Basically, I have a structure like "project/dir1/dir2" that I know will always be exactly those three directories, with the same names, in that order. What may not be the same is how deep this structure is nested; for example you could have:

$HOME/project/dir1/dir2

or

$HOME/workspace/project/dir1/dir2

Basically I need a general way to locate the project/dir1/dir2 structure no matter how far deeply buried it is.

This will always be on Ubuntu. I thought about using locate, but then I'd have to guarantee that the locate db is always up to date.

1 Answer 1

12

If you used find -name project/dir1/dir2 you will find a message like this:

find: warning: Unix filenames usually don't contain slashes (though pathnames do). That means that -name 'project/dir1/dir2' will probably evaluate to false all the time on this system. You might find the -wholename test more useful, or perhaps -samefile. Alternatively, if you are using GNU grep, you could use find ... -print0 | grep -FzZproject/dir1/dir2'`.

So, it offers certain alternatives for such task. Weird it doesn't mention the -path command to find:

find -path "*/project/dir1/dir2" -print

Please, notice the */ at the beginning. These tells find to print any path that ends with /project/dir1/dir2 and the name of the first directory has to be project otherwise it will find myproject/dir1/dir2 and such.

2
  • This seems to work. I tried it earlier and it didn't work but I'm away from my Ubuntu install and was trying to prototype this on an OS X machine. Works on my *nix machine. I should have expected that the BSD find wouldn't work the same. Nov 1, 2013 at 21:46
  • this worked with MacOS if specifying the root dir to search. i.e. find /home/ -path "*/project/dir1/dir2" -print
    – jakethedog
    Mar 5, 2019 at 21:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .