这里的问题是必须完成文件夹重命名的顺序。最深的文件夹必须首先重命名,并且重命名过程必须向上进行,直到到达顶层文件夹。这样做的唯一方法是通过递归子例程以这种方式处理每个现有文件夹:
Rename the files in this folder.
For each folder in this folder:
Process it recursively.
Rename it.
另外,请注意,并非所有文件/文件夹都必须重命名,只有名称中有空格的文件/文件夹;否则 REN 命令会发出错误。下面的批处理文件将第一个参数作为要处理的顶级文件夹:
@echo off
setlocal EnableDelayedExpansion EnableExtensions
pushd %1
call :ProcessThisFolder
popd
exit /b
:ProcessThisFolder
REM Rename the files in this folder.
for %%f in (*.*) do (
set "old=%%f"
set new=!old: =_!
if not !new! == !old! ren "!old!" "!new!"
)
REM For each folder in this folder:
for /D %%d in (*) do (
REM Process it recursively.
cd %%d
call :ProcessThisFolder
cd ..
REM Rename it.
set "old=%%d"
set new=!old: =_!
if not !new! == !old! ren "!old!" "!new!"
)
编辑
原始方法的问题是执行重命名的顺序。假设dir /s /b ...的结果是:
C:\Users\Tin\Desktop\renameFolders\file 1.txt
C:\Users\Tin\Desktop\renameFolders\file 2.txt
C:\Users\Tin\Desktop\renameFolders\folder 1
C:\Users\Tin\Desktop\renameFolders\folder 1\file 3.txt
C:\Users\Tin\Desktop\renameFolders\folder 1\folder 2
当第 3 行被处理时,folder 1 被重命名为folder_1,所以此时第 4 行和第 5 行中的名称不再有效。第一次重命名必须在file 3.txt 和folder 2 上完成,然后向上到上面的文件夹,但dir 命令显示的行按字母顺序排序,其他可用的顺序在这种情况下没有帮助。
上面程序的第一部分是这样工作的:
pushd %1 Save current directory and do a CD %1
call :ProcessThisFolder Call the subroutine defined in this same file below
popd Do a CD to the directory saved by previous PUSHD
exit /b Terminate here this Batch file; otherwise the lines
. . . below would be executed again
您可以通过使用 /? 来查看任何命令的操作?参数,例如:pushd /?。