How to sort lines of a text file containing version numbers in format major.minor.build.revision numerical?

后端 未结 5 731
忘掉有多难
忘掉有多难 2020-12-04 04:06

I have a txt file with values like this:

3.6.4.2
3.6.5.1
3.6.5.10
3.6.5.11
3.6.5.12
3.6.5.13
3.6.5.2
3.6.7.1
3.6.7.10
3.6.7.11
3.6.7.2
3.6.7.3
5条回答
  •  时光取名叫无心
    2020-12-04 04:32

    This is a common problem in Batch files. All sorting methods use a string comparison, where "10" comes before "2", so it is necessary to insert left zeros in the numbers less than 10. The Batch file below do that, but instead of generate a new file with the fixed numbers, it uses they to create an array that will be automatically sorted. After that, the array elements are shown in its natural (sorted) order.

    EDIT: I modified the code in order to manage two digits numbers in the four parts.

    @echo off
    setlocal EnableDelayedExpansion
    
    for /F "tokens=1-4 delims=." %%a in (input.txt) do (
        rem Patch the four numbers as a two digits ones
        set /A "a=100+%%a, b=100+%%b, c=100+%%c, d=100+%%d"
        rem Store line in the proper array element
        set "line[!a:~1!!b:~1!!c:~1!!d:~1!]=%%a.%%b.%%c.%%d"
    )
    
    rem Show array elements
    for /F "tokens=2 delims==" %%a in ('set line[') do echo %%a
    

    Output:

    3.6.4.2
    3.6.5.1
    3.6.5.2
    3.6.5.10
    3.6.5.11
    3.6.5.12
    3.6.5.13
    3.6.7.1
    3.6.7.2
    3.6.7.3
    3.6.7.10
    3.6.7.11
    

提交回复
热议问题