“sort -h”无法正常工作

meh*_*dad 6 command-line sort command

我尝试对这个文件进行排序:

1000000911M
1G
2G
1.5G
100M

Run Code Online (Sandbox Code Playgroud)

但使用sort -h file我得到:

100M
1000000911M
1G
1.5G
2G
Run Code Online (Sandbox Code Playgroud)

排序有问题吗?如果是这样,如何避免这种情况而无需显式扩展 M,G ?

Sot*_*oce 14

这在手册页中有记录sort:

-h, --human-numeric-sort, --sort=human-numeric
         Sort by numerical value, but take into account the SI suffix, if present.
         Sort first by numeric sign (negative, zero, or positive); then by SI
         suffix (either empty, or `k' or `K', or one of `MGTPEZY', in that order);
         and finally by numeric value.  The SI suffix must immediately follow the
         number.  For example, '12345K' sorts before '1M', because M is "larger"
         than K.  This sort option is useful for sorting the output of a single
         invocation of 'df' command with -h or -H options (human-readable).
Run Code Online (Sandbox Code Playgroud)

相关部分是第四句:

For example, '12345K' sorts before '1M', because M is "larger" than K.
Run Code Online (Sandbox Code Playgroud)

这是你在你的1000000911M线和1G它2G后面的线之间观察到的。

在通常的实践中,生成具有此类后缀的输出的软件将切换后缀而不是输出这么多有效数字。

  • 例如`numfmt --from=iec --to=iec <infile | sort -h` 可能有帮助。 (2认同)