如何对包含格式为major.minor.build.revision数字的版本号的文本文件的行进行排序? [英] How to sort lines of a text file containing version numbers in format major.minor.build.revision numerical?

查看:17
本文介绍了如何对包含格式为major.minor.build.revision数字的版本号的文本文件的行进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含如下值的 txt 文件:

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

我需要编写一个批处理脚本并返回一个排序的输出.问题出在最后一列,数字 .10 和 .11 应该在 .3 之后,等等.我需要最新版本"在底部,在这种情况下是 3.6.7.11

I need to write a batch script and return a sorted output. The problem is with last column, numbers .10 and .11 should go after .3 and so. I need the "latest version" to be on the bottom, which in this case is 3.6.7.11

在 Linux 中,我使用了 "sort -t"." -k1n,1 -k2n,2 -k3n,3 -k4n,4" 但我无法使用批处理脚本.

In Linux I used "sort -t"." -k1n,1 -k2n,2 -k3n,3 -k4n,4" but I can't get it working with batch script.

此外,由于某些原因,我不允许使用 Cygwin 或 PowerShell.

Also I am not allowed to use Cygwin or PowerShell for some reasons.

在我的批处理代码中,到目前为止,我只尝试了各种版本,但对我没有任何效果:

In my batch code I am so far trying only various versions of this but nothing is working for me:

sort /+n versions.txt

这个问题中使用的输出很简单

The output used in this question is simply

sort versions.txt

看起来这个命令排序是正确的,直到我没有使用 2 位数字.

It looks like that command sort is doing it correctly until I don't have 2 digits number used.

推荐答案

这是 Batch 文件中的常见问题.所有排序方法都使用 string 比较,其中10"在2"之前,因此需要在小于 10 的数字中插入左零.下面的批处理文件这样做,但不是用固定数字生成一个新文件,它使用它们来创建一个 array 将自动排序.之后,数组元素以其自然(排序)的顺序显示.

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

输出:

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

这篇关于如何对包含格式为major.minor.build.revision数字的版本号的文本文件的行进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆