【发布时间】:2019-10-15 19:00:39
【问题描述】:
我有一个文件夹,其中包含数百个Name, ID 格式的子文件夹。这些文件夹中的每一个都包含几个子文件夹,其中一些文件夹的名称中包含空格。我想通过用下划线替换空格来仅重命名子文件夹而不是父文件夹,例如C:\Location\John, 1234\My Documents 到 C:\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。
【问题讨论】:
-
是否总是要替换空间的“叶子”(最低的子文件夹,下面没有其他文件夹)?
-
是的,没错。
-
如果您想在
C:\Tydelik\Name, ID"以下的所有子目录级别中用下划线替换所有空格,您可能需要确定每个级别的最低级别分支,并在升级时重命名每个级别。想象一下有C:\Tydelik\John, 1234\My Documents\Work Files,如果你的代码首先重命名My Documents,即C:\Tydelik\John, 1234\My_Documents,那么最初解析的子目录C:\Tydelik\John, 1234\My Documents\Work Files将不复存在,因为它将是C:\Tydelik\John, 1234\My_Documents\Work Files。因此Work Files可能需要先处理。 -
我只是快速检查了一下,所有文件夹的最低级别是 C:\Tydelik\John, 1234\X 其中 X 是我的文档、图片、视频等。在此之下没有其他文件夹。
标签: windows batch-file