批处理:重命名所有文件和子文件夹

时间:2011-11-11 11:29:37

标签: loops batch-file rename

for /f "tokens=*" %%f in ('dir /ad /s /b "C:\Users\Tin\Desktop\renameFolders"') do (
setlocal enabledelayedexpansion enableextensions
  set N=%%f
  set N=!N: =_!
  ren "%%f" "!N!"
)

如何重命名所有文件和子文件夹? 我无法遍历并重命名所有子文件夹。

文件结构: 测试:

file 2.txt
file 1.txt
folder 1
test.bat

文件夹1:

folder 2
file 3.txt

文件夹2: file 4.txt

2 个答案:

答案 0 :(得分:2)

我认为你有三个问题:

  1. 使用/ ad开关意味着您只会处理目录而不是文件
  2. set N=%%f会导致N获取包含路径的全名,因为这是dir /b返回的内容
  3. 递归需要逆转。如果您将“文件夹1”重命名为“folder_1”,那么当您检查“文件夹1 /文件夹2”时,该路径将不再有效。
  4. 修复(1)只是移除/ad 修复(2)是使用set N=%%~nxf 我不确定如何修复#3。我偶然发现用(1)&amp ;;重复运行脚本(2)修复后最终将所有文件重命名。但我确信那里有更好的答案。

答案 1 :(得分:2)

这里的问题是ORDER,必须完成文件夹的重命名。必须首先重命名最深的文件夹,并且重命名过程必须继续向上,直到到达顶级文件夹。唯一的方法是通过递归子例程以这种方式处理每个现有文件夹:

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.txtfolder 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 /?