Zsh: sort globs in natural order with the (n) glob qualifier

Globs sort filenames character by character, so numbered files often come out in a surprising order, with 10 before 2. Zsh has a neat fix for this: the n glob qualifier, which applies a “natural” sort, treating any run of digits as a number rather than a string of characters.
I found this feature useful when building a PDF from multiple files.n I exported my multi-page document from Inkscape to one PNG per page, named Page 1.png, Page 2.png, and so on. I then stitched them into a single PDF with ImageMagick:
$ magick *.png document.pdf
But when I opened document.pdf, the pages were jumbled: page 10 came straight after page 1. That made no sense!
To debug, I checked what the glob expanded to, using print -l to print each match on its own line:
$ print -l *.png
Page 1.png
Page 10.png
Page 11.png
Page 12.png
Page 2.png
Page 3.png
...
There it was: Page 10.png came before Page 2.png, because the character 1 sorts before 2.
Adding the n glob qualifier makes Zsh sort numbers by their numeric value, giving “natural” order:
$ print -l *.png(n)
Page 1.png
Page 2.png
Page 3.png
...
Page 10.png
Page 11.png
Page 12.png
I used the qualifier in the ImageMagick command:
$ magick *.png(n) document.pdf
…and my PDF came out in proper order.
Make it the default
If you always want natural ordering, enable the NUMERIC_GLOB_SORT option in your ~/.zshrc:
setopt numeric_glob_sort
Then all globs sort numerically, no qualifier needed:
$ magick *.png document.pdf
This is what I’ve done, and I’ve had no issues in a few years of using it.
Reverse order
n only changes how names compare, so you can combine it with the other sorting qualifiers. For example, On sorts by name, descending, so (nOn) gives reverse natural order:
$ print -l *.png(nOn)
Page 12.png
Page 11.png
Page 10.png
Page 9.png
...
Page 1.png
This could be useful if you want to flip a series of files, for example.
Read my book Boost Your Django DX, freshly updated in November 2024.
One summary email a week, no spam, I pinky promise.
Related posts:
- Zsh: find the largest files with the
(OL)glob qualifier - Zsh: select generated files with
(om[1])glob qualifiers - Zsh: list recently modified files with
(m0)glob qualifiers
Tags: zsh