-1

I am using lsof on MacOS to receive a list of files. The execution takes around a minute to finish. I could use grep but that wouldn't improve the execution time of lsof.

Does lsof support a regex/filter option to ignore certain paths? I can only find filter options for network connections.

% time lsof +D /Users/jack/
[...]
... 60.128s total

Any input is highly appreciated.

HelloWorld
  • 2,392
  • 3
  • 31
  • 68
  • 1
    Is it the [`-d` flag](https://stackoverflow.com/questions/15548653/how-to-exclude-from-lsof-output-the-libraries)? [Man page](https://linux.die.net/man/8/lsof) also seems to describe this. – kelsny Oct 23 '22 at 01:45
  • Thanks! I tried it but it doesn't seem to be compatible with `+D` as it is ignored. – HelloWorld Oct 23 '22 at 02:32
  • I just read `"Then there are exclusion and inclusion members in the set. lsof reports them as errors and exits with a non-zero return code."` So it seems including a directory and excluding certain files ins't possible – HelloWorld Oct 23 '22 at 02:36
  • What shell are you using? –  Oct 29 '22 at 02:44
  • I use `zsh` and `bash` – HelloWorld Oct 29 '22 at 15:19

1 Answers1

0

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.