shellgnu-sort

sort does not work with -h with text file


In my OS, I can find

-h, --human-numeric-sort
compare human readable numbers (e.g., 2K 1G)

And I have a file aaa.txt:

2M
5904K
1G

Then I type

sort -h aaa.txt

The output is

5904K
2M
1G

It's wrong. It should be

2M
5904K
1G

Questions:

  1. Why does sort -h not work? The result is wrong even in lexicographically order perspective. How to sort the aaa.txt file in human readable numbers.
  2. Or it can work only with du -h? But the most vostes answer seems can work with awk.
  3. With du -h, sort does not need to specify which field, like sort -k1h,1 ? Why? What would happend if the memory size is not in the first field?

Solution

  • Why does sort -h not work?

    Below is a comment from GNU sort's source code.

    /* Compare numbers ending in units with SI xor IEC prefixes
           <none/unknown> < K/k < M < G < T < P < E < Z < Y
       Assume that numbers are properly abbreviated.
       i.e. input will never have both 6000K and 5M.  */
    

    It's not mentioned in the man page, but -h is not supposed to work with your input.

    How to sort the aaa.txt file in human readable numbers.

    You can use numfmt to perform a Schwartzian transform as shown below.

    $ numfmt --from=auto < aaa.txt | paste - aaa.txt | sort -n | cut -f2
    2M
    5904K
    1G