I am just wondering if I have modified the source and target location appropriately on using code posted in answer on How to copy files into folders based on first 15 characters of file and folder name?
I can't get it to run. I am just trying to create a folder named the first 9 characters and move all files with matching first 9 characters into that folder.
@echo off
setlocal EnableExtensions
set "SourceFolder=C:\PRASINUS\July #2"
set "TargetFolder=C:\PRASINUS\Test 1"
rem Call subroutine CopyFile for each non hidden and
rem non system file found in specified source folder
rem and then exit processing of this batch file.
for %%I in ("%SourceFolder%*") do call :CopyFile "%%~fI"
endlocal
goto :EOF
rem This is a subroutine called for each file in source folder.
rem It takes the first 9 characters from each file name passed
rem to this subroutine via first parameter and search for a
rem folder in target folder starting with same 9 characters.
rem If such a folder is found, the file is copied to this folder
rem and the subroutine is exited.
rem Otherwise a new folder is created for the file and if
rem this is indeed successful, the file is copied into the
rem newly created folder with an appropriate message.
:CopyFile
set "FileName=%~n1"
set "DirectoryName=%FileName:~0,9%"
for /D %%D in ("%TargetFolder%\%DirectoryName%*") do (
copy /B /Y %1 /B "%%~D\" >nul
goto :EOF
)
set "NewFolder=%TargetFolder%\%DirectoryName%_new"
md "%NewFolder%"
if exist "%NewFolder%\" (
echo Created new folder: %NewFolder%
copy /B /Y %1 /B "%NewFolder%\" >nul
goto :EOF
)
echo Failed to create folder: %NewFolder%
echo Could not copy file: %1
goto :EOF