gpt4 book ai didi

linux - 如何使用 Unix 排序命令按列中人类可读的数字文件大小进行排序?

转载 作者:太空狗 更新时间:2023-10-29 11:06:44 25 4
gpt4 key购买 nike

这个问题现在有了答案 - 滚动到这篇文章的末尾寻找解决方案。

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

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

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

我在 CentOS Linux 机器上,版本 7.2.1511。 sort 的版本是“sort (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

最佳答案

您的“m”和“g”单位应该是大写的。 GNU sort manual阅读:

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

Sort numerically, 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; see Block size); and finally by numeric value.

您可以像这样使用 GNU sed 更改 curl 的输出:

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'

关于linux - 如何使用 Unix 排序命令按列中人类可读的数字文件大小进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55926142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com