The following code options should offer some speedup.
Most of the time is spent expanding the directories.
If tree
is not available you can install it with Homebrew:
brew install tree
Replace regex with your regular expression.
Regex:
tree -d -i -f /Users/jack | grep regex | while read dirs; do lsof +d $dirs; done
Pattern matching:
tree -d -i -f -P pattern /Users/jack | while read dirs; do lsof +d $dirs; done
Caching
If the directories do not change you can cache the directories to a file:
tree -d -i -f /Users/jack | grep regex > dirs.txt
and then use the following to list the open files:
cat dirs.txt | while read dirs; do lsof +d $dirs; done
A recursive version by limiting depth to 1:
tree -d -i -f -L 1 $nextdir | grep regex
...is possible and may be faster for sparse trees with a high pruning rate, but the overhead would make it infeasible to implement for large scale depths.