给定混合文本和数字的输入(没有前导零),我怎样才能让它按“自然”顺序排序?例如,给定以下输入(主机名):
whatever-1.example.org
whatever-10.example.org
whatever-11.example.org
whatever-12.example.org
whatever-13.example.org
whatever-2.example.org
whatever-3.example.org
whatever-4.example.org
whatever-5.example.org
whatever-6.example.org
whatever-7.example.org
whatever-8.example.org
whatever-9.example.org
我想要这个输出:
whatever-1.example.org
whatever-2.example.org
whatever-3.example.org
whatever-4.example.org
whatever-5.example.org
whatever-6.example.org
whatever-7.example.org
whatever-8.example.org
whatever-9.example.org
whatever-10.example.org
whatever-11.example.org
whatever-12.example.org
whatever-13.example.org
编辑
我应该提到,除了“无论什么”之外,还有
thingaroo-#.example.org
.
:
blargh-#.example.org
.
:
...etc...
谢谢!
答案1
如果您的 GNU coreutils ≥ 7.0,则可以使用版本排序。这是字典顺序,只不过数字序列根据其十进制整数值进行排序。
sort -V
答案2
可以成功地对特定类型的输入进行排序
sort -t - -nk2,2
但如果您正在寻找的话,它并不能真正推广到所有类型的文件名。
答案3
抱歉,我没有提供原始问题中所需的所有信息。所有的答案都对我找到我真正想要的东西很有用。我最终使用的是:
sort -t- -k1,1 -k2,2
在哪里:
-t- divide the hostnames into fields using dash (-) rather than spaces
-k1,1 the first sort key is the first field (from 1 to 1), a normal sort
-k2,2 the second key is the second field using a numeric (n) sort
(the field includes the ".example.org" but the numeric sort
seems to cope find with the trailing non-number chars)
结果如下:
blargh-1.example.org
:
blargh-13.example.org
thingaroo-1.example.org
:
thingaroo-17.example.org
whatever-1.example.org
:
whatever-13.example.org
答案4
sort -t- -k2n file
whatever-1.example.org
whatever-2.example.org
whatever-3.example.org
whatever-4.example.org
whatever-5.example.org
whatever-6.example.org
whatever-7.example.org
whatever-8.example.org
whatever-9.example.org
whatever-10.example.org
whatever-11.example.org
whatever-12.example.org
whatever-13.example.org