首页 > 解决方案 > 如何使用 Unix 排序命令按列中人类可读的数字文件大小排序?

问题描述

现在回答了这个问题 - 滚动到这篇文章的末尾以获得解决方案。

抱歉,如果答案已经在这里,但到目前为止我发现的所有答案都建议使用 -h 标志或 -n 标志,而且这些都不适合我......

我有一些 curl 命令的输出,它给了我几列数据。其中一列是人类可读的文件大小(“1.6mb”、“4.3gb”等)。

我正在使用 unix排序命令按相关列排序,但它似乎试图按字母顺序而不是数字顺序排序。我曾尝试同时使用 -n 和 -h 标志,但尽管它们确实改变了顺序,但在这两种情况下,数字上的顺序都不是正确的。

我在 CentOS Linux 机器上,版本 7.2.1511。我拥有的排序版本是“排序(GNU coreutils)8.22”。

我尝试以这些不同的格式使用 -h 标志:

curl localhost:9200/_cat/indices | sort -k9,9h | head -n5
curl localhost:9200/_cat/indices | sort -k9 -h | head -n5
curl localhost:9200/_cat/indices | sort -k 9 -h | head -n5
curl localhost:9200/_cat/indices | sort -k9h | head -n5

我总是得到这些结果:

green open indexA            5 1        0       0   1.5kb    800b
green open indexB            5 1  9823178 2268791 152.9gb  76.4gb
green open indexC            5 1    35998    7106 364.9mb 182.4mb
green open indexD            5 1      108      11 387.1kb 193.5kb
green open indexE            5 1        0       0   1.5kb    800b

我尝试使用与上述相同格式的 -n 标志:

curl localhost:9200/_cat/indices | sort -k9,9n | head -n5
curl localhost:9200/_cat/indices | sort -k9 -n | head -n5
curl localhost:9200/_cat/indices | sort -k 9 -n | head -n5
curl localhost:9200/_cat/indices | sort -k9n | head -n5

我总是得到这些结果:

green open index1      5 1     1021       0   3.2mb   1.6mb
green open index2      5 1     8833       0   4.1mb     2mb
green open index3      5 1     4500       0     5mb   2.5mb
green open index4      1 0        3       0   3.9kb   3.9kb
green open index5      3 1  2516794       0   8.6gb   4.3gb

编辑:原来有两个问题:

1) sort 期望看到大写的单个字母 - M、K 和 G 而不是 mb、kb 和 gb(对于字节,你可以留空)。

2) sort 将包括前导空格,除非您明确排除它们,这会导致排序混乱。

解决方案是将小写字母替换为大写字母并使用 -b 标志进行排序忽略前导空格(我将此答案基于下面的@Vinicius 解决方案,因为如果您不知道正则表达式,它更容易阅读):

curl localhost:9200/_cat/indices | tr '[kmg]b' '[KMG] ' | sort -k9hb

标签: linuxsortingunix

解决方案


你的“m”和“g”单位应该是大写的。GNUsort手册如下:

-h --human-numeric-sort --sort=human-numeric

按数字排序,首先按数字符号(负数、零或正数);然后按 SI 后缀(按顺序为空,或“k”或“K”,或“MGTPEZY”之一;参见块大小);最后是数值。

您可以像这样更改curlGNU的输出sed

curl localhost:9200/_cat/indices \
| sed 's/[0-9][mgtpezy]/\U&/g'
| sort -k9,9h \
| head -n5

产量:

green open index4      1 0        3       0   3.9kb   3.9kb
green open index1      5 1     1021       0   3.2Mb   1.6Mb
green open index2      5 1     8833       0   4.1Mb     2Mb
green open index3      5 1     4500       0     5Mb   2.5Mb
green open index5      3 1  2516794       0   8.6Gb   4.3Gb

其他字母如“b”将被视为“无单位”:

green open indexA            5 1        0       0   1.5kb    800b
green open indexE            5 1        0       0   1.5kb    800b
green open indexD            5 1      108      11 387.1kb 193.5kb
green open indexC            5 1    35998    7106 364.9Mb 182.4Mb
green open indexB            5 1  9823178 2268791 152.9Gb  76.4Gb

如果需要,您可以通过管道将已排序输出中的单位更改回小写sed 's/[0-9][MGTPEZY]/\L&/g'


推荐阅读