3

The batch file below recursively echos files and folders while adding some simple formatting, such as indenting to show the recursion depth, adding "/ " before folder names, "*" before certain files, and skipping folders named "Archive". It works great except that files and folders are sorted randomly, rather than alphabetically. How could this be changed to sort both files and folders alphabetically?

@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
4

2 回答 2

5

需要很少的改变。将 FOR 循环转换为 FOR /F 运行排序的 DIR 命令。该/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.

于 2013-02-20T19:26:11.850 回答
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....
    )
)
于 2013-02-20T19:09:54.693 回答