批处理文件:按字母顺序对文件夹和文件进行排序

3
以下批处理文件可以递归地输出文件和文件夹,并添加一些简单的格式,如缩进以显示递归深度,在文件夹名称前添加“/”,在某些文件名前添加“*”,并跳过名为“Archive”的文件夹。它的功能很棒,但是文件和文件夹的排序是随机的,而不是按字母顺序排序。如何更改以按字母顺序排序文件和文件夹?
@echo off
setlocal disableDelayedExpansion
pushd %1
set "tab=   "
set "indent="
call :run
exit /b

:run

REM echo the root folder name
for %%F in (.) do echo %%~fF
echo ------------------------------------------------------------------

set "folderBullet=\"
set "fileBullet=*"

:listFolder
setlocal

REM echo the files in the folder
for %%F in (*.txt *.pdf *.doc* *.xls*) do echo %indent%%fileBullet% %%F  -  %%~tF

REM loop through the folders
for /d %%F in (*) do (

  REM skip "Archive" folder
  if /i not "%%F"=="Archive" (

  REM if in "Issued" folder change the file bullet
  if /i "%%F"=="Issued" set "fileBullet= "

  echo %indent%%folderBullet% %%F
  pushd "%%F"
  set "indent=%indent%%tab%"
  call :listFolder

  REM if leaving "Issued folder change fileBullet
  if /i "%%F"=="Issued" set "fileBullet=*"

  popd
))
exit /b
2个回答

5

需要做很少的更改。将FOR循环转换为运行排序DIR命令的FOR /F。选项/A-D仅列出文件,而/AD仅列出目录。

此版本按名称对文件进行排序。

@echo off
setlocal disableDelayedExpansion
pushd %1
set "tab=   "
set "indent="
call :run
exit /b

:run

REM echo the root folder name
for %%F in (.) do echo %%~fF
echo ------------------------------------------------------------------

set "folderBullet=\"
set "fileBullet=*"

:listFolder
setlocal

REM echo the files in the folder
for /f "eol=: delims=" %%F in (
  'dir /b /a-d /one *.txt *.pdf *.doc* *.xls* 2^>nul'
) do echo %indent%%fileBullet% %%F  -  %%~tF

REM loop through the folders
for /f "eol=: delims=" %%F in ('dir /b /ad /one 2^>nul') do (

  REM skip "Archive" folder
  if /i not "%%F"=="Archive" (

  REM if in "Issued" folder change the file bullet
  if /i "%%F"=="Issued" set "fileBullet= "

  echo %indent%%folderBullet% %%F
  pushd "%%F"
  set "indent=%indent%%tab%"
  call :listFolder

  REM if leaving "Issued folder change fileBullet
  if /i "%%F"=="Issued" set "fileBullet=*"

  popd
))
exit /b

如果想先按文件类型排序,再按名称排序,只需将/ONE更改为/OEN


3
尝试更改你的for /d循环,将其从:
for /d %%F in (*) do

为了

for /f "delims=" %%F in ('dir /b /o:n *.') do

尝试更改排序方式,看是否有所不同。实际上,按名称排序是dir的默认行为,因此您可能可以轻松应对。

for /f "delims=" %%F in ('dir /b *.') do

如果您的目录名称中含有点号,您需要稍作修改。
for /f "delims=" %%F in ('dir /b') do (
    rem Is this a directory?
    if exist "%%F\" (
        rem do your worst....
    )
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接