Batch file that can index and rename files in multiple subfolders, resetting the index every time the loop goes into a new folder

こ雲淡風輕ζ 提交于 2020-01-06 19:30:33

问题


I am in the process of writing a batch file that can quickly run through a root folder, We'll just say "C:\SomeMusic\" that has a lot of subfolders and files in it. What I'm looking to do is to rename just the files in each folder, but in a sequential way (ex. somefile1.ext, somefile2.ext ...)

I have this right now, but I do not know how to reset my counter if the loop goes into a new directory

SET COUNT=0
setlocal ENABLEDELAYEDEXPANSION
FOR /R %%X IN (*.mp3) DO (
    SET /A COUNT=!COUNT!+1
    SET FN=%%~nxX
    ECHO Renamed "!FN!" to "song!COUNT!.mp3"
    REN %%X song!COUNT!.mp3
)
:EOF
endlocal
PAUSE

On a quick sidenote: If I run the Rename command like this, it will name the files "song1.mp3", "song2.mp3" "song3.mp3" regardless of what their name used to be?


回答1:


You need to keep track of the current directory, and reset the counter every time it changes:

setlocal ENABLEDELAYEDEXPANSION
FOR /R %%X IN (*.mp3) DO (
    IF NOT "%%~dpX"=="!LASTPATH!" (SET /A COUNT=0) ELSE (SET /A COUNT=!COUNT!+1)
    SET LASTPATH=%%~dpX
    REN "%%X" song!COUNT!.mp3
)
endlocal

Note that the resultant filename will be songX.mp3. If you need the file to maintain its original name, use this rename code:

REN "%%X" "%%~nX!COUNT!%%~xX"


来源:https://stackoverflow.com/questions/15375123/batch-file-that-can-index-and-rename-files-in-multiple-subfolders-resetting-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!