Search code examples
cmdcopyrenamebatch-rename

Copy and rename music files with batch file


I have a music directory in the format of D:%Artist%%Album%\Song.mp3. from here, i have created a script that prompts for an artist folder and then copies all MP3s into a new folder with the same name after stripping any album folders

D:\%Artist%\%Album%\Song.mp3 into D:\MP3s\%Artist%\Song.mp3

What i'd really like to do is rename all song files in the new location to include the Album name followed by an underscore. if there a song is in the Artist root folder, it should just have an underscore before the song name to indcate it wasn't within an album folder.

D:\%Artist%\%Album%\%Song% into D:\MP3s\%Artist%\%Album%_Song.mp3 OR D:\MP3s\%Artist%\_Song.mp3

the following code is what i'm using to get all songs from all subfolders into a single folder, but i am unsure on how to get the albun name setup for a rename process. this is my current code

SET /P Artist=What is the artist folder to copy?
pushd D:\Music\%Artist%
for /r %%a in (*.mp3) do (
COPY "%%a" "D:\Music\MP3s\%%~nxa"
)
popd

Solution

  • I found that the following code works in my case. if you have a different file structure depth, then you will need to adjust the tokens. i also found that if the script was run multiple times for the same artist, it would copy over the files but not rename them, so i have added in a file check to see if the final filename is already present.

    SETLOCAL enabledelayedexpansion
    SET /P Artist=What is the artist folder to copy?
    MD "D:\Music\MP3s\%Artist%"
    PUSHD D:\Music\%Artist%
    FOR /r %%a in (*.mp3) DO (
    FOR /f "tokens=4,5 delims=\" %%I IN ("%%a") DO (
    SET Song=%%J
    SET Album=%%I
    if "!Song!" == "" (
    SET Song=!Album!
    SET Album=
    )
    SET NewFileName="!Album!_!Song!"
    )
    CD D:\Music\MP3s\%Artist%
    IF NOT EXIST !NewFileName! (
    COPY "%%a" "D:\Music\MP3s\%Artist%\%%~nxa"
    REN "D:\Music\MP3s\%Artist%\%%~nxa" !NewFileName!
    )
    )
    POPD