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"
asked Feb 13, 2017 at 23:35
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. Commented Feb 14, 2017 at 22:37
  • @dave_thompson_085 I suggest to make your comment an answer Commented Feb 15, 2017 at 21:17

1 Answer 1

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.

answered Feb 14, 2017 at 21:30
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. Commented Feb 14, 2017 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. Commented Feb 15, 2017 at 15:39

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.