开发者

Mixed lexicographic and numeric sorting

开发者 https://www.devze.com 2023-01-30 17:57 出处:网络
I have a list such as: input.txt foo.bar.1 foo.bar.2 foo.bar.3.x.y.z foo.bar.10 foo.bar.0 baz.10.qux baz.3.qux

I have a list such as:

input.txt

foo.bar.1
foo.bar.2
foo.bar.3.x.y.z
foo.bar.10
foo.bar.0
baz.10.qux
baz.3.qux

that needed to be sorted. I need to treat this as a dot separated fields, where numeric fields are needed to be sorted numerically.

So I wrote:

mixsort.py

#!/usr/bin/env python
import sys
seq = map(lambda l: map(lambda s: (s.isdigit() and [int(s)] or [s])[0], l),
          [ s.rstrip().split('.') for s in sys.stdin.readlines() ])
seq.sort()
sys.stdout.write( '\n'.join(['.'.join([str(i) for i in l]) for l in seq]) )

usage

$ mixsort.py < input.txt
baz.3.qux
baz.1开发者_如何学Python0.qux
foo.bar.0
foo.bar.1
foo.bar.2
foo.bar.3.x.y.z
foo.bar.10

But am I re-inventing the wheel here? Is there a common *nix utility that do what I need? is there a switch to sort(1) that will help me out. (note that the position of the numeric fields is unknown). Is there a better way to do the same thing?


coreutils version 8.7

Use version sort: sort -V:

Input:

frayser@gentoo ~ $ cat /tmp/list.ran
foo.bar.1
foo.bar.2
baz.10.qux
baz.3.qux
foo.bar.0
foo.bar.3.x.y.z
foo.bar.10

Sort:

frayser@gentoo ~ $ LC_ALL=C sort -V /tmp/list.ran
baz.3.qux
baz.10.qux
foo.bar.0
foo.bar.1
foo.bar.2
foo.bar.3.x.y.z
foo.bar.10

 

I found this in the info pages as suggested in the manpage: info coreutils "sort invocation"

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号