1

Im trying to use the find command to recursively search a directory tree and return all results with a directory matching a given name.

find . -type d -name '<NAME>'

I get a list of paths returned which are printed into a log file. I want to be able to omit any results which contain a file called omit.txt within a parent directory.

./parent_directory/ NAME>

I have been trying to do it with the following

find . -type d -name '<NAME>' \( ! -wholename "*omit.txt*" -prune \)

I am trying to use the prune command to omit results containing the file, but I think this may only work with directories. Any help would be greatly appreciated. I am trying to do this in just one command and maintain the output file as much as possible -

  • So, if we have ./a/x/omit.txt and ./b/x/foo.txt, you'd want a listing that only contains ./b/x/? Can you add a mock-up sample directory tree and the expected output on the question? – ilkkachu Jan 24 '18 at 10:12
  • So in a directory tree where the is ./a ./b ./c and each of those directories contains a directory called d, giving ./a/d ./b/d ./c/d. if i was to place a file called omit.txt into directory c, /i want to try and use the find unix command to return any case where there is directory called 'd' in the directory tree AND the file 'omit.txt' is not present within the parent directory. So you would expect it to return './a/d ./b/d' . , with my attempt above it returns './a/d ./b/d ./c/d' – Bobby Brennan Jan 24 '18 at 10:25
2

I don't think you can do this completely within find, since you need to be able to see the file inside the directory when processing the directory. -prune has to operate on the directory itself, but -path and other conditions only see the file name after find has already descended to the directory.

All I can come up with is to fork off a shell to peek inside the directory. Something like this:

$ mkdir -p x y/z ; touch x/foo y/omit.txt
$ find -type d \( -exec sh -c '[ -e "$1/omit.txt" ]' sh {} \; -prune -o -print \)
.
./x

foo -o bar does not evaluate bar if foo succeeds, so if the directory is pruned, the print doesn't run. Add -o -print to the end to print the directory contents too. We can't use exec ... {} + here, since we need this to act as a condition for each directory separately.

  • Now that I see this I remember seeing a similar answer/question here some months back that took the same approach. Don't have time to find it now, though. ;) – B Layer Jan 24 '18 at 10:31
  • Thanks, you gave me a lot to work with here, I think I will read up on some of the arguments you used here. Thanks – Bobby Brennan Jan 24 '18 at 10:45

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.