KLARTEXT GUIDE

How to sort lines in a text file

In KlarText, choose Edit ▸ Text Transforms ▸ Sort Lines (A→Z), or (Z→A) to reverse it. With text selected, only those lines are sorted; with nothing selected, the whole document is.

Sorting lines is one of those jobs that comes up constantly and always in the middle of something else: alphabetising a .gitignore, ordering a list of names, tidying a config file, putting a bibliography in order.

The Terminal way

sort input.txt > output.txt

Reliable, and it has the usual friction: a second file and a mv, because sort cannot write to the file it is reading. It also sorts the entire file. If you only wanted lines 40 to 60 sorted and the rest left alone, sort is the wrong shape of tool and you are into sed -n ranges and reassembling the file from pieces.

There is a subtler catch too. sort follows your locale, and LC_ALL=C sort follows byte order, and the two disagree — most visibly on capitals and on accented characters:

sort names.txt          # locale order: Ähre, apple, Banana
LC_ALL=C sort names.txt # byte order:   Banana, apple, Ähre

Byte order puts every capital letter before every lowercase one and dumps accented characters at the end, which is almost never what a reader means by “alphabetical”.

The KlarText way

Edit ▸ Text Transforms ▸ Sort Lines (A→Z)

or Sort Lines (Z→A) for descending order.

Sorting is case-insensitive and locale-aware: apple, Ähre and Banana land where a reader expects them, not where their byte values put them. Capitals do not jump to the front.

Sort just part of a file. Select the lines you want ordered and the transform applies to that selection alone, expanded to whole lines. The rest of the document is untouched. With nothing selected the whole document is sorted. This is the case that makes the shell awkward and the editor easy.

One ⌘Z undoes the sort.

Sort and deduplicate

The shell’s sort -u does both at once. In KlarText it is two menu items:

  1. Edit ▸ Text Transforms ▸ Sort Lines (A→Z)
  2. Edit ▸ Text Transforms ▸ Remove Duplicate Lines

Worth knowing: if you only want duplicates gone and the original order kept, skip step 1 — Remove Duplicate Lines preserves order on its own. See how to remove duplicate lines on Mac.

Before you sort

If the file has trailing whitespace, lines that look identical may not be, which matters as soon as you deduplicate. Run Strip Trailing Whitespace first.

Related