Sort file name with delimiter in batch file

2019-09-08 03:09发布

I need to sort the list of file names by their version number with least first, in windows batch script. The file names are like:

2_0_0to2_0_1
2_0_1_to2_0_2
...
2_0_12_to2_0_13
...

I've tried dir and sort in Windows but it seems to only look at char positions which wouldn't work in the case of double digits. In Linux, I've done this with: ls *.txt | sort -n -t _ -k1 -k2 -k3. How to do this on Windows. Please help. Thanks!

1条回答
祖国的老花朵
2楼-- · 2019-09-08 03:36

Try this:

@ECHO OFF &SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%x IN (*) DO (
    FOR /f "tokens=1-6delims=_to" %%a IN ("%%~x") DO (
        SET "g1=0%%a"
        SET "g2=0%%b"
        SET "g3=0%%c"
        SET "g4=0%%d"
        SET "g5=0%%e"
        SET "g6=0%%f"
        SET "$!g1:~-2!!g2:~-2!!g3:~-2!!g4:~-2!!g5:~-2!!g6:~-2!=%%~x"
    )
)
FOR /f "tokens=2delims==" %%a IN ('set "$"') DO ECHO %%~a
查看更多
登录 后发表回答