Remove Duplicate Lines & Sort Lines · Tutorial

How to sort file names in natural order

4 min readbeginnerUpdated

You sorted a list of numbered files and got chapter1, chapter10, chapter11, chapter2, which is technically alphabetical but not what anyone wants. This tutorial shows the difference between alphabetical and natural sorting, and how to get chapter2 before chapter10 every time.

What you need

Steps

  1. Paste the list

    Paste one file name per line into the left box. The sample has seven Markdown files in a jumbled order, including Chapter1.md with a capital C.

  2. See the problem with A → Z

    Choose A → Z. The result puts chapter10.md and chapter11.md before chapter2.md, because alphabetical sorting compares one character at a time, and 1 comes before 2.

    appendix.md
    Chapter1.md
    chapter10.md
    chapter11.md
    chapter2.md
    chapter20.md
    chapter3.md
  3. Switch to natural order

    Choose Natural (file2 before file10). Numbers are now compared by their value, so the chapters run 1, 2, 3, 10, 11, 20. Because Case-sensitive is off, Chapter1.md sorts in with the others despite its capital letter.

    appendix.md
    Chapter1.md
    chapter2.md
    chapter3.md
    chapter10.md
    chapter11.md
    chapter20.md
  4. Use the sorted list

    Copy the result into a table of contents, a build script or a playlist. To avoid the problem in future, you can also name files with leading zeros, such as chapter02.md, which sort correctly everywhere.

Try it yourself

Opens the Remove Duplicate Lines & Sort Lines with this tutorial's sample loaded.

Try it now

Common mistakes

Using natural order for codes with leading zeros
In natural order 007 and 7 are equal in value. If leading zeros matter, as in some product codes, use A → Z instead.
Mixed separators
Natural sorting compares runs of digits. v1.10 sorts after v1.9, but a list mixing v1-10 and v1.9 may not sort the way you expect. Make the format consistent first.
Expecting case-sensitive sorting
With Case-sensitive off, capitals are ignored for ordering. Turn it on if Chapter and chapter should be grouped separately.

Next steps

Go back to the Remove Duplicate Lines & Sort Lines, or keep going with one of these:

FAQ

Does my file manager sort naturally?

Most modern file managers, including Windows Explorer and macOS Finder, sort file names naturally by default. Many command-line tools and programming languages don't.