How to filter out certain files from the output set of lsof on macOS?

200 views Asked by At

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.

1

There are 1 answers

0
AudioBubble On

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.