Zsh: find the largest files with the (OL) glob qualifier

Got a directory that you want to tidy up bloat from? Whether you’re trying to find bad build artifacts in your work repository or clear out old cat videos from your home directory, Zsh’s (OL) glob qualifier can help you find the largest files.
Using the Django source repository as an example, here’s how we can show the size of the five largest files:
$ du -h **/*(.OL[1,5])
696K tests/gis_tests/data/rasters/raster.numpy.txt
492K docs/_theme/djangodocs/static/fontawesome/webfonts/fa-brands-400.svg
440K Django.egg-info/SOURCES.txt
396K tests/admin_views/tests.py
320K build/lib/django/contrib/admin/static/admin/js/vendor/xregexp/xregexp.js
Glob qualifier syntax is dense. Let’s break it down:
du -h:dureports the disk usage of each file, and its-hoption makes the sizes human-readable (KiB, MiB, etc.)**/*: a recursive glob pattern that matches all files in the current directory and its subdirectories.(): parentheses following a glob pattern contain the glob qualifiers, which filter and sort the matches..: select only plain files, excluding directories.O: sort the matches, descending.L: by file size (“length”).[1,5]: select only the first five matches. Increase5to see more results.
With this list, we have a nice starting point to investigate trimming down the repository’s cloned size (at least for shallow clones, common in CI and build environments).
Filter by minimum size
The standalone L glob qualifier can selects files by size, when combined with two things:
- An optional unit:
kfor KiB,mfor MiB. The default unit is bytes, which makes numbers verbose, so you’ll probably wantkorm. - A prefixed number, where
+nmeans “more than n” and-nmeans “less than n”.
So, for example, to find all Python files over 150 KiB, listed largest first, we can use (.Lk+150OL) (note the end has a zero followed by a letter O):
$ du -h **/*.py(.Lk+150OL)
396K tests/admin_views/tests.py
296K tests/migrations/test_operations.py
248K tests/schema/tests.py
236K tests/forms_tests/tests/test_forms.py
216K tests/migrations/test_autodetector.py
184K tests/queries/tests.py
Wow, Django has some big tests!
The glob is **/*.py: match all Python files recursively.
That mega glob qualifier is:
.: select only plain files.L: select by file size.k: use KiB as the unit.+150: select only files larger than 150 KiB.O: sort the matches, descending.L: by file size (“length”).
The power of tersity, hey?
Learn how to make your tests run quickly in my book Speed Up Your Django Tests.
One summary email a week, no spam, I pinky promise.
Related posts:
- Zsh: select generated files with
(om[1])glob qualifiers - Zsh: list recently modified files with
(m0)glob qualifiers
Tags: zsh