如何仅重命名子文件夹而不更改父文件夹名称

时间:2019-10-15 09:09:38

标签: windows batch-file

我有一个文件夹,其中包含数百个子文件夹,格式为Name, ID。这些文件夹中的每一个都包含几个子文件夹,其中一些子文件夹的名称中包含空格。我想通过用下划线替换空格来仅重命名子文件夹而不重命名父文件夹,例如C:\Location\John, 1234\My DocumentsC:\Location\John, 1234\My_Documents

我尝试修改此处找到的一段脚本,但它也会更改父文件夹

这是未编辑的代码:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "StartFolder=C:\Tydelik"

cd /D %SystemRoot%
set "RenameError="

rem Rename all folders containing at least one space character in folder name.
for /F "delims=" %%I in ('dir "%StartFolder%\* *" /AD /B /S 2^>nul') do call :RenameFolder "%%I"

if defined RenameError echo/& pause
rem Restore initial environment and exit this batch file.
endlocal
goto :EOF


:RenameFolder
set "NewFolderName=%~nx1"
set "NewFolderName=%NewFolderName: =_%"

set "FolderPath=%~dp1"
if not exist "%FolderPath%" set "FolderPath=%FolderPath: =_%"
set "FullFolderName=%FolderPath%%~nx1"
if not exist "%FullFolderName%\" set "RenameError=1" & goto :EOF

for %%J in ("%FullFolderName%") do set "FolderAttributes=%%~aJ"
if "%FolderAttributes:~3,1%" == "h" %SystemRoot%\System32\attrib.exe -h "%FullFolderName%"

ren "%FullFolderName%" "%NewFolderName%" 2>nul
if errorlevel 1 goto ErrorFolderRename

if "%FolderAttributes:~3,1%" == "h" %SystemRoot%\System32\attrib.exe +h "%FolderPath%%NewFolderName%"
goto :EOF

:ErrorFolderRename
echo Error renaming folder "%FullFolderName%"
set "RenameError=1"
if "%FolderAttributes:~3,1%" == "h" %SystemRoot%\System32\attrib.exe +h "%FullFolderName%"
goto :EOF

正如我所说,每个子文件夹的预期输出应为C:\Location\John, 1234\My_Documents而不是C:\Location\John, 1234\My Documents。当前使用我拥有的代码,我得到C:\Tydelik\John,_1234\My_Documents

2 个答案:

答案 0 :(得分:1)

虽然Compo的解决方案将文件夹重命名为“ depth = 2”,但仅重命名了“ leafes”(树的最后一个文件夹,“ depth = last”)。我采用了call的方法来避免扩展延迟和由此引起的可能的问题(文件夹名称为!的情况-在您的情况下不太可能,但是永远都不知道...)

@echo off
setlocal
set "sourcedir=..\..\"
for /f "delims=" %%I in ('dir "%sourcedir%" /ad /b /s 2^>nul') do call :RenameFolder "%%I"
goto :eof

:RenameFolder
dir /ad /b /s "%~1" 2>nul | find /v "" >nul && goto :eof  ::skip renaming, if a subfolder exists
set "leaf=%~nx1"
ECHO ren "%~1" "%leaf: =_%"
goto :eof

注意:出于安全原因,我仅通过回显禁用了ren命令。如果可以正常工作,请删除ECHO

答案 1 :(得分:0)

这是我想寻找的示例,基于您仅对重命名"C:\Tydelik\Name, ID"的子目录感兴趣,而对那些子目录中没有的内容感兴趣的事实。

@Echo Off
SetLocal DisableDelayedExpansion
Set "SourceDir=C:\Tydelik"
For /F "EOL=?Delims=" %%A In ('Dir /B/AD "%SourceDir%" 2^>NUL'
)Do Set "TargetDir="&For /F "EOL=?Delims=" %%B In (
    'Dir /B/AD "%SourceDir%\%%A" 2^>NUL') Do (Set "TargetDir=%%B"
    SetLocal EnableDelayedExpansion
    If Not "!TargetDir: =!"=="!TargetDir!" (
        Ren "%SourceDir%\%%A\%%B" "!TargetDir: =_!")
    EndLocal)