提前感谢您的帮助。 我有一个文件夹,其中包含大量随机命名的子文件夹。这些子文件夹中有许多带有编号文件名的文件。例如..
\ParentFolder\UniqueFolderName\0001.ogg
\ParentFolder\UniqueFolderName\0002.ogg
\ParentFolder\UniqueFolderName\0003.ogg
\ParentFolder\DifferentFolderName\0001.ogg
\ParentFolder\DifferentFolderName\0002.ogg
\ParentFolder\DifferentFolderName\0003.ogg
我想从 \ParentFolder\ 运行一个批处理文件,它可以重命名 .ogg 文件以继承唯一的文件夹名称,并最终得到类似这样的结果...
\ParentFolder\UniqueFolderName\UniqueFolderName - 0001.ogg
\ParentFolder\UniqueFolderName\UniqueFolderName - 0002.ogg
\ParentFolder\UniqueFolderName\UniqueFolderName - 0003.ogg
\ParentFolder\DifferentFolderName\DifferentFolderName - 0001.ogg
\ParentFolder\DifferentFolderName\DifferentFolderName - 0002.ogg
\ParentFolder\DifferentFolderName\DifferentFolderName - 0003.ogg
这可能是非常简单的事情。但我的小脑袋无法弄清楚如何在不将批处理文件放入每个子文件夹中的情况下执行此操作。
这可以通过以下注释的批处理代码来完成:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Run in a separate command process started by FOR with cmd.exe /C the
rem command DIR to get a list of non-hidden *.ogg files in bare format
rem with just full qualified file name (drive + path + name + extension)
rem in specified directory and all its subdirectories.
rem This list is captured by FOR and processed line by line with disabling
rem the default line splitting behavior of __FOR__. The subroutine RenameFile
rem is called with each full qualified file name enclosed in double quotes.
for /F "delims=" %%I in ('dir "\ParentFolder\*.ogg" /A-D-H /B /S 2^>nul') do call :RenameFile "%%I"
rem Restore initial environment resulting in deletion of all
rem environment variables used in the subroutine below.
endlocal
rem Exit processing of this batch file with suppressing the
rem error message output on command extensions are disabled
rem in the initial environment on starting the bath file.
exit /B 2>nul
:RenameFile
rem Get just file name without drive, path and extension.
set "FileName=%~n1"
rem Get just drive and path of file name ending with a backslash.
set "FilePath=%~dp1"
rem Get name of folder containing the file.
for %%J in ("%FilePath:~0,-1%") do set "FolderName=%%~nxJ"
rem Exit the subroutine if file name contains already the folder name.
echo "%FileName%" | %SystemRoot%\System32\find.exe /I "%FolderName% - " >nul 2>nul
if not errorlevel 1 goto :EOF
rem Exit the subroutine if there is already a file or folder
rem with new file name in the folder of the current file.
if exist "%FilePath%%FolderName% - %FileName%%~x1" goto :EOF
rem Rename the file by prepending it with folder name, space, hyphen, space.
ren %1 "%FolderName% - %FileName%%~x1"
goto :EOF
要了解所使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完整、仔细地阅读每个命令显示的帮助页面。
call /?
dir /?
echo /?
endlocal /?
exit /?
find /?
for /?
goto /?
if /?
rem /?
ren /?
setlocal /?
另请参阅:GOTO :EOF 返回到哪里?