我需要在文件夹中 dir 我的文件,但分拣机与Windows资源管理器中显示的不一样。
例如,如果文件夹中包含112
和0113
文件名的文件,
控制台窗口中的 dir 按顺序列出0113
和112
。
如何在Windows资源管理器中列出在命令提示符窗口中按数字排序的目录中的文件名?
答案 0 :(得分:1)
此批处理代码可能有助于将文件名输出排序为数字。请仔细阅读评论专栏,因为有一些限制。注释行是以命令rem
开头的行。
@echo off
setlocal EnableExtensions
rem Get from current directory all file names without path not enclosed
rem in double quotes sorted alphabetically and not numeric as wanted and
rem pass them to subroutine AddToFileList enclosed in double quotes.
for /F "delims=" %%I in ('dir * /A-D /B /ON 2^>nul') do call :AddToFileList "%%I"
rem The file names are now in an environment variables list. Output
rem this file names list. The split in environment variable and file
rem name without path works only if the file name does not contain
rem itself an equal sign.
for /F "tokens=1* delims==" %%I in ('set FileList[ 2^>nul') do echo %%J
rem Delete all local environment variables and restore previous
rem environment with the initial list of environment variables.
endlocal
rem Exit batch processing to avoid an unwanted fall through to the
rem subroutine AddToFileList.
exit /B
rem The subroutine AddToFileList is for adding each file found
rem into an environment variables array based on the file name.
rem The array works only for files with up to 5 digits in file number,
rem i.e. for file numbers in range 0 to 99999. That should be enough.
:AddToFileList
rem Get just the file name without path and without file extension.
set "FileName=%~n1"
rem In case of name of file has only 1 point and no characters left
rem this point, the file name is the point and the file extension.
rem Such file names are not common on Windows, but exist often on *nix.
if "%FileName%" == "" set "FileName=%~x1"
set "FileNumber="
:GetFileNumber
for /F "delims=0123456789" %%I in ("%FileName:~-1%") do goto AddFileToArray
set "FileNumber=%FileName:~-1%%FileNumber%"
set "FileName=%FileName:~0,-1%"
if not "%FileName%" == "" goto GetFileNumber
:AddFileToArray
set "FileNumber=00000%FileNumber%"
set "FileNumber=%FileNumber:~-5%"
set "FileList[%FileName%_%FileNumber%]=%~1"
rem Exit the subroutine and continue in FOR loop in main batch code block.
goto :EOF
要了解使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。
call /?
dir /?
echo /?
endlocal /?
exit /?
for /?
goto /?
if /?
rem /?
set /?
setlocal /?
另请参阅Microsoft文章Using command redirection operators,了解2^>nul
2>nul
的解释,>
重定向运算符^
与{{1}}一起转义以获取重定向用于执行命令 DIR 和 SET 。如果没有与当前目录树中的文件名模式* .txt匹配的文件,则此重定向会抑制 DIR 和 SET 输出的错误消息。