[英]How to sort file names numerically in windows command line?
The windows explorer does display in correct order. Windows资源管理器确实以正确的顺序显示。 For example: filename1.txt, filename2.txt, filename11.txt etc. When I tried the DIR command with different options could not get the same behaviour.
例如:filename1.txt,filename2.txt,filename11.txt等。当我尝试使用不同选项的DIR命令时,无法获得相同的行为。 It displays filename1.txt, filename11.txt, filename2.txt.
它显示filename1.txt,filename11.txt,filename2.txt。
Is there any way to sort it so that numeric ordering is preserved? 有什么方法可以对它进行排序,以便保留数字顺序?
@ECHO Off
:: dir list in numeric-value order
SETLOCAL
:: %1= directoryname; default current directory
SET "targetdir=%~1"
IF NOT DEFINED targetdir SET "targetdir=.\*.*"
:: remove variables starting $
FOR /F "delims==" %%a In ('set $ 2^>Nul') DO SET "%%a="
SET /a maxnumlength=0
SET "manyzeroes=0000000000000000"
SET "manyzeroes=%manyzeroes%%manyzeroes%%manyzeroes%%manyzeroes%"
:: analyse list of filenames
FOR /f "delims=" %%a IN (
'dir /b /a-d "%targetdir%" '
) DO CALL :detnlen "%%a"
:: build list of filenames
FOR /f "delims=" %%a IN (
'dir /b /a-d "%targetdir%" '
) DO CALL :setname "%%a"
FOR /F "tokens=1*delims=:" %%a In ('set $ 2^>Nul') DO ECHO %%b
GOTO :EOF
:detnlen
SET "name=%~1"
SET /a numlength=0
SET "action=L"
:detnloop
IF %action%==F SET "action=B"
SET "post=%name:~0,1%"&SET "name=%name:~1%"
IF "%post%" geq "0" IF "%post%" leq "9" (
SET /a numlength+=1
SET "action=F"
)
IF %action% neq B IF DEFINED name GOTO detnloop
IF %numlength% gtr %maxnumlength% SET /a maxnumlength=%numlength%
GOTO :EOF
:setname
SET "name=%~1"
SET "pre="
SET "nums="
SET "action=L"
:snloop
IF %action%==F SET "action=B"
SET "post=%name:~0,1%"&SET "name=%name:~1%"
IF "%post%" geq "0" IF "%post%" leq "9" (
SET /a numlength+=1
SET "action=F"
SET "nums=%nums%%post%"
)
IF %action%==L SET "pre=%pre%%post%"&SET "post="
IF %action% neq B IF DEFINED name GOTO snloop ELSE SET "post="
IF %action%==F SET "post="
IF DEFINED nums SET "nums=%manyzeroes%%nums%"
IF DEFINED nums CALL SET "nums=%%nums:~-%maxnumlength%%%"
SET "$%pre%%nums%%post%%name%=:%~1"
GOTO :EOF
Oh, my! 天啊!
There are no inbuilt switches to show the directory in that odd way, but this has all the hallmarks of a challenge. 没有内置的开关以这种奇怪的方式显示目录,但这具有挑战的所有特征。
OK - it's insanely slow, but it appears to work. 好的-速度非常慢,但似乎可以正常工作。
The principle is to determine the longest sequence of initial-numerics as maxnumlength
then assign the name of the detected file to an environment variable starting $
and with a name constructed from the filename with the numeric part leading-zero-padded. 原理是确定最长的初始数字序列为
maxnumlength
然后将检测到的文件的名称分配maxnumlength
$
开头的环境变量,并使用从文件名构造的名称,其数字部分以前导零填充。 set $
then lists the $
variables in alphabetic order; set $
然后按字母顺序列出$
变量; select the value, which is the original filename. 选择值,即原始文件名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.