4

I want to execute a find search with multiple maxdepths, depending on the directory.

Is this possible? It seems that -maxdepth is "global", but I was curious if there is some workaround.

(I'm aware it's possible to execute two separate commands, but using one would be faster, and it would keep the calling code simpler)

7
  • Why not use two find commands?
    – pfnuesel
    Sep 10, 2017 at 15:41
  • I've considered that, but before that, I wanted to try a single run, for both performance and sorting reasons.
    – Marcus
    Sep 10, 2017 at 15:42
  • 3
    It would not keep the code simpler.
    – Kusalananda
    Sep 10, 2017 at 15:48
  • FreeBSD find supports syntax like find dir1 dir2 \( -path 'dir1/*' -depth 1 -prune \) -o \( -path 'dir2/*' -depth 2 -prune \) -o -print Sep 12, 2017 at 20:38
  • @TavianBarnes this is in fact the answer given below :-)
    – Marcus
    Sep 13, 2017 at 21:19

2 Answers 2

7

You can sort of emulate it using -prune on different matching pathnames. For example, to match /etc to depth 1, and /lib to depth 2:

find /etc /lib/ \
    \( -regex '/etc/[^/]*/.*'       -prune \) \
 -o \( -regex '/lib/[^/]*/[^/]*/.*' -prune \) \
 -o -print

You need to be careful to add the last line to print or otherwise operate on the remaining files and directories.

5

No, you can’t apply different -maxdepth options to different parts of a series of find tests. Since it’s a global option, as you point out, it applies to all the tests. If you specify multiple -maxdepth options, the last one is taken into account and applied to the whole command.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .