Hone

Lessons · Terminal · sort -n: 9 before 100

sort compares text until you tell it otherwise

Plain sort orders character by character, so 105 comes before 12 the way ab comes before b. -n compares them as numbers.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

This is the single commonest wrong answer a pipeline gives, and it looks sorted, which is why nobody notices.

How to think about it

Any time the thing being sorted is a number, -n.

Worked example

sort nums.txt
105, 12, 8. Sorted, as text.
sort -n nums.txt
8, 12, 105. Sorted, as numbers.
sort -rn nums.txt
-r reverses, so largest first. -nr is the same thing.

Your turn

Sort the lines of app.log as numbers.

sort  app.log

The trap

Counts are numbers too. Leaving -n off the end of a counting pipeline puts 9 above 100.

Practise sort -n: 9 before 100 on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.