1

Suppose I have a directory with a bunch of files:

/file1.png
/directory1/file1.png
/directory1/file2.png
/directory1/file3.txt
/file2.txt
/directory2/file1.png
/directory2/file2.txt
/directory2/file3.gif

Is there a way you can recursively traverse the directories looking for files using --include and --exclude?

It would be great to find something as simply as:

find . --include "*.png" --exclude "file1.png"
2
  • 3
    For this simple case find . -name "*.png" '!' -name "file1.png" -- note the quoting of ! is not always needed but simpler to play it safe. For more complicated cases you can do full Boolean logic using -a -o ( ) (where bottom-level -a can be implicit as here) as described on the man page; again ( ) usually need quoting. Feb 14 '17 at 22:37
  • @dave_thompson_085 I suggest to make your comment an answer
    – janos
    Feb 15 '17 at 21:17
2

To exclude a file, either use a more restrictive regex than *.png or grep the output to exclude a result:

find . -name "*.png" | grep -v "file1.png"

You can exclude a whole directory tree by using the -prune option, but it doesn't exclude on a file level.

2
  • I've never seen a find that takes --include or in fact any double-hyphen; ITYM -name or maybe -path but those take a pattern not a regex; your example "*.png" is a (properly quoted) pattern and not a regex. Some finds do take -regex with an actual regex. Feb 14 '17 at 22:38
  • You're right, I was just quoting some of the original post without checking too much. I'll edit to correct it.
    – woolfie
    Feb 15 '17 at 15:39

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.