Search code examples
batch-filebatch-rename

Batch file to split filenames and use part for new subdir to move into


I have a few thousand photographs in a single folder all named with the pattern persons name - location.jpg, e.g. John Doe - Mountain.jpg. I'm looking for a batch file that will create folders based on the first part of the file name and move that file and all of the other matching file names into that folder, giving an end result of all of John Doe's pictures in his folder.


Solution

  • @ECHO OFF
    SETLOCAL
    SETLOCAL ENABLEDELAYEDEXPANSION
    SET "sourcedir=U:\sourcedir"
    SET "destdir=U:\destdir"
    FOR /f "delims=" %%a IN (
      'dir /b /a-d "%sourcedir%\*-*.jpg" '
      ) DO (
     FOR /f "tokens=1*delims=-" %%p IN ("%%a") DO (
      echo(MD "%destdir%\%%p"
      echo(MOVE "%sourcedir%\%%a" "%destdir%\%%p"
     )
    )
    
    GOTO :EOF
    

    You would need to change the settings of sourcedir and destdir to suit your circumstances.

    The required MD commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(MD to MD to actually create the directories. Append 2>nul to suppress error messages (eg. when the directory already exists)

    The required MOVE commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(MOVE to MOVE to actually move the files. Append >nul to suppress report messages (eg. 1 file moved)

    Note that the terminating space in the directory name is of no relevance.