Login
You're viewing the assemblag.es public feed.
  • Oct 5, 2026, 10:35 AM

    I've just run into a situation where I wished that 'sort -n' had an option to treat the numeric sort field as being hex, rather than decimal.

    Now that I think about it, this seems like such a natural thing to want that I'm surprised I've never had a need for it before!

    💬 1🔄 2⭐ 5

Replies

  • Oct 5, 2026, 10:40 AM

    It would _almost_ work to turn '-n' into an option that says: first sort by length, and then sort lexicographically within strings of the same length. That would correctly sort non-negative integers in any number base at all without needing to be told which base, as long as the digits are represented by characters whose ASCII ordering matches their semantic ordering. It would even correctly ignore 0x prefixes on hex numbers, if there were any.

    Not quite, though. That policy wouldn't handle negative numbers, so you'd still have to make a special case for a leading minus sign. And if you were sorting non-integers, then you'd have to spot a decimal point, separate that and everything after it, and use that as a tertiary sort criterion. Ugh.

    💬 1🔄 0⭐ 0
  • 💬 0🔄 0⭐ 0
  • Oct 5, 2026, 10:43 AM

    @jernej__s thank you, I hadn't spotted sort -g at all. I searched the man page for 'hex', which of course didn't find that option.

    But it still doesn't do what I want (and I'm not entirely sure what it _is_ doing). In my sort output, I can see that it thinks 74 < 75c < 76 (suggesting that it's ignoring the alphabetic suffix), and also 400000 < 1e8, suggesting that it's considering exponential float notation!

    💬 0🔄 0⭐ 0
  • 💬 1🔄 0⭐ 0
  • 💬 0🔄 0⭐ 0
  • Oct 5, 2026, 10:43 AM

    @simontatham if your hex numbers start with 0x and you're using GNU sort, then you can do this with the "-g" or "--general-numeric-sort" options.

    💬 1🔄 0⭐ 0
  • Oct 5, 2026, 10:44 AM

    @pozorvlak alas, they don't! I could preprocess the file, but then, if I'm doing that I could convert into decimal just as easily.

    💬 0🔄 0⭐ 2
  • Oct 5, 2026, 5:02 PM

    @simontatham Preprocessing the file sort of feels like the Unix Way(TM). Could even be via a pipe if you don't feel like writing the intermediary. @pozorvlak

    💬 0🔄 0⭐ 1
  • Oct 5, 2026, 6:07 PM

    @simontatham although..... I guess this would involve converting back to hex after the sort if you want the same answers, which does complicate my simple sounding solution @pozorvlak

    💬 0🔄 0⭐ 1
  • 💬 0🔄 0⭐ 0
  • Oct 5, 2026, 10:48 AM

    @simontatham I'm sure you know this, but the order you've just described is called "shortlex order". Alas, sort(1) doesn't appear to support it.

    💬 0🔄 0⭐ 0