-1

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?
oguz ismail
  • 1
  • 16
  • 47
  • 69

1 Answers1

3

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
oguz ismail
  • 1
  • 16
  • 47
  • 69
  • Thanks! Can you answer the 3rd quetition: do not neeed to specify field to sort? – tranquil.coder May 28 '20 at 11:55
  • I have this question because `If no key fields are specified, sort uses a default key of the entire line.`, [gnu manual](https://www.gnu.org/software/coreutils/manual/html_node/sort-invocation.html). So, `-h` will take the first field default, not the entire line. Is it right? – tranquil.coder May 28 '20 at 13:22
  • can you help to solve [this](https://stackoverflow.com/questions/62066148/sort-the-entire-line-contains-blank)? – tranquil.coder May 28 '20 at 13:40