Search code examples
windowsbatch-filereorganize

Batch create folder based on partial file name and move files to folder


I have a series of .wav files with similar file names. Each file has a first and last name followed by the date and a number. I would like to create a series of files based on the first and last name and then move the files to the matching file path.

Example:

John_Doe_1-6-6-2021 15-23_123453245.wav
John_Doe_1-6-6-2021 15-23_12345874.wav
John_Doe_1-6-6-2021 15-23_1239964.wav

Mary_Walker_1-6-6-2021 15-23_123453245.wav
Mary_Walker_1-6-6-2021 15-23_1778941.wav
Mary_Walker_1-6-6-2021 15-23_8741556899.wav

I would like those files to be organized similar to the following:

SourceDirectory
 |> John_Doe_1
     |> John_Doe_1-6-6-2021 15-23_123453245.wav
     |> John_Doe_1-6-6-2021 15-23_12345874.wav
     |> John_Doe_1-6-6-2021 15-23_1239964.wav

 |> Mary_Walker_1
   |> Mary_Walker_1-6-6-2021 15-23_123453245.wav
   |> Mary_Walker_1-6-6-2021 15-23_1778941.wav
   |> Mary_Walker_1-6-6-2021 15-23_8741556899.wav

At the moment I have this script. The script will create a folder based on the First Name and moves the files there (Which is great), the only issue is I need the first name, last name and the 1 at the end. So the Folder should be like John Doe 1 not just John or John Doe.

@echo off
SETLOCAL
SET "sourcedir=C:\Users\JohnUser\Desktop\Test\"
PUSHD %sourcedir%
FOR /f "tokens=1*" %%a IN (
 'dir /b /a-d "* *_*-* *.*"'
 ) DO (  
 MD %%a
MOVE "%%a %%b" .\%%a\
)
POPD
GOTO :EOF

pause

Solution

  • Here's a quick example using the - character as the delimiter, Delims, to perform the fiilename string split. (You could use Tokens=1, but as that is the default, I have left it out):

    @Echo Off
    SetLocal EnableExtensions
    Set "SourceDir=%UserProfile%\Desktop\Test"
    For /F "Delims=" %%G In (
        '%SystemRoot%\System32\where.exe "%SourceDir%":"?*-?*-?*-???? ??-??_?*.wav"'
    ) Do For /F "Delims=-" %%H In ("%%~nG") Do (
        %SystemRoot%\System32\Robocopy.exe "%SourceDir%" "%SourceDir%\%%H" "%%~nxG" /Mov 1>NUL
    )
    

    To understand how any command works, open a Command Prompt window, type Command /?. For example for /?, where /?, robocopy /?.