Shell – Find a particular nesting of directory names, e.g. …/project/dir1/dir2

directoryfindshell-script

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.

Best Answer

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.

Related Question