How can I sort file names by version numbers?

前端 未结 7 1209
轮回少年
轮回少年 2020-12-05 13:23

In the directory \"data\" are these files:

command-1.9a-setup
command-2.0a-setup
command-2.0c-setup
command-2.0-setup

7条回答
  •  悲&欢浪女
    2020-12-05 13:54

    Another way to do this is to pad your numbers.

    This example pads all numbers to 8 digits. Then, it does a plain alphanumeric sort. Then, it removes the pad.

    $ pad() { perl -pe 's/(\d+)/0000000\1/g' | perl -pe 's/0*(\d{8})/\1/g'; }
    $ unpad() { perl -pe 's/0*([1-9]\d*|0)/\1/g'; }
    $ cat files | pad | sort | unpad
    command-1.9a-setup
    command-2.0-setup
    command-2.0a-setup
    command-2.0c-setup
    command-10.1-setup
    

    To get some insight into how this works, let's look at the padded sorted result:

    $ cat files | pad | sort
    command-00000001.00000009a-setup
    command-00000002.00000000-setup
    command-00000002.00000000a-setup
    command-00000002.00000000c-setup
    command-00000010.00000001-setup
    

    You'll see that with all the numbers nicely padded to 8 digits, the alphanumeric sort puts the filenames into their desired order.

提交回复
热议问题