I'm trying to use the find command to generate a list of source files within a directory and only some of its subdirectories. Example:


I want a list of files ending in '.c' and '.h', and I want to exclude the contents of the /exclude subdirectory.

find -name '*.c' -o -name '*.h' -o -path '*/exclude' -prune produces this output:


How can I use find to produce the above list without "./exclude"?

  • 1
    This is due to implicit print of find results. Add an explicit -print (or -printf) to the files that must be printed and pruned directories won't be printed anymore. See Stéphane Chazelas' answer. – xhienne Aug 1 '17 at 21:44
find . -name excludeme -prune -o \
  \( -name '*.c' -o -name '*.h' \) -print

Remember that AND (implicit) has precedence over OR (-o). (see also -name '*.[ch]')

| improve this answer | |

At the cost of some extra filesystem operations limit the search to plain files. This will exclude the exclude directory because that's not a file:

find . \( -name '*.c' -o -name '*.h' -o -path '*/exclude' -prune \) -type f
| improve this answer | |

This command returns what you ask:

find . \( -name '*.c' -o -name '*.h' \) -a \! \( -path './exclude/*' \)

| improve this answer | |
  • But still descends into ./exclude only to exclude all the files (except those that contain invalid characters) in it. – Stéphane Chazelas Aug 1 '17 at 21:34

The simplest change is to replace -prune (don't look no more in this directory), with -prune -false (don't look no more in this directory, and this is not a match).

| improve this answer | |

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.