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
- The Remove Duplicate Lines & Sort Lines
- A list of names that contain numbers (the Try it button loads chapter files)
Steps
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.mdwith a capital C.See the problem with A → Z
Choose A → Z. The result puts
chapter10.mdandchapter11.mdbeforechapter2.md, because alphabetical sorting compares one character at a time, and1comes before2.appendix.md Chapter1.md chapter10.md chapter11.md chapter2.md chapter20.md chapter3.mdSwitch 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.mdsorts in with the others despite its capital letter.appendix.md Chapter1.md chapter2.md chapter3.md chapter10.md chapter11.md chapter20.mdUse 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.
Common mistakes
- Using natural order for codes with leading zeros
- In natural order
007and7are 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.10sorts afterv1.9, but a list mixingv1-10andv1.9may 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
Chapterandchaptershould 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.