3

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:

/Source_Files
    /dontexclude
        dontexclude.h
        dontexclude.c
    /exclude
        exclude.c
        exclude.h
    main.c
    test.c
    test.h

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:

./test.h
./exclude
./test.c
./main.c
./dontexclude/dontexclude.c
./dontexclude/dontexclude.h

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
5
find . -name excludeme -prune -o \
  \( -name '*.c' -o -name '*.h' \) -print

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

0

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
0

This command returns what you ask:

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

  • 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
0

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).

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.