Sort version strings on bash

后端 未结 2 1944
轮回少年
轮回少年 2020-12-21 16:12

Example content of STRINGS.txt:

    3.0.3
    3.0.11.2
    3.0.11.1
    3.0.11
    3.0.16
    3.0.15.1
    3.0.15
    3.0.14
    3.0.10.3
    3.0.10.2
    3.         


        
2条回答
  •  有刺的猬
    2020-12-21 17:05

    I know you don't want Python solution, but for those who lack GNU sort (such as OS X) it sure is an easy way to do this.

    Given:

    $ echo "$a"
    3.0.3
    3.0.11.2
    3.0.11.1
    3.0.11
    3.0.16
    3.0.15.1
    3.0.15
    3.0.14
    3.0.10.3
    3.0.10.2
    3.0.10.1
    3.0.13.1
    3.0.10
    3.0.13
    3.0.9
    3.0.12
    3.0.8
    3.0.7.2
    3.0.7.1
    3.0.7
    3.0.9.2
    3.0.9.1
    3.0.2
    3.0.8.1
    3.0.6.1
    3.0.6
    3.0.5
    3.0.1
    3.0.0
    

    Python 1 liner:

    $ echo "$a" | python -c '
    import sys, re; print "".join(sorted(sys.stdin.readlines(), key=lambda s: map(int, re.findall("\\d+", s)), reverse=True))'
    3.0.16
    3.0.15.1
    3.0.15
    3.0.14
    3.0.13.1
    3.0.13
    3.0.12
    3.0.11.2
    3.0.11.1
    3.0.11
    3.0.10.3
    3.0.10.2
    3.0.10.1
    3.0.10
    3.0.9.2
    3.0.9.1
    3.0.9
    3.0.8.1
    3.0.8
    3.0.7.2
    3.0.7.1
    3.0.7
    3.0.6.1
    3.0.6
    3.0.5
    3.0.3
    3.0.2
    3.0.1
    3.0.0
    

提交回复
热议问题