@echo off
setlocal
if "%~1" == "test" call :test
for /d /r %%F in (*) do (
for /d %%G in ("%%F\*") do (
for %%H in ("%%~G\*.EXT") do (
call :move "%%~H" "%%~F"
)
)
)
exit /b
:move
setlocal
if /i not exist "%~2\%~nx1" (
echo 1. move "%~1" "%~2"
move "%~1" "%~2"
exit /b
)
set "name=%~n1"
for /l %%I in (1 1 9) do (
if "%name:~-4%" == " (%%I)" (
set "name=%name:~0,-4%"
)
)
for /l %%I in (1 1 9) do (
if not exist "%~2\%name% (%%I)%~x1" (
echo 2. move "%~1" "%~2\%name% (%%I)%~x1"
move "%~1" "%~2\%name% (%%I)%~x1"
exit /b
)
)
exit /b
:test
if exist "Main Folder" rd /s /q "Main Folder"
call :prep "Main Folder\Folder2\Folder3a" "File1.EXT"
call :prep "Main Folder\Folder2\Folder3b" "File2.EXT"
call :prep "Main Folder\Folder2\Folder3c" "File3.EXT"
call :prep "Main Folder\Folder2\Folder3d" "File1.EXT"
call :prep "Main Folder\Folder3\Folder3a" "File1.EXT"
call :prep "Main Folder\Folder3\Folder3b" "File2.EXT"
call :prep "Main Folder\Folder3\Folder3c" "File3.EXT"
call :prep "Main Folder\Folder3\Folder3d" "File1.EXT"
pushd "Main Folder" || exit /b 1
echo Prepared to test.
pause
exit /b
:prep
if /i not exist "%~1" md "%~1"
if /i not exist "%~1\%~2" type nul > "%~1\%~2"
exit /b
Test code intregrated makes it easier to test.
Remove the test code if desired.
Test using test
as 1st argument i.e. main.cmd test
.
Based from loop you posted in How to create batch file that move files from sub-folder up one level renaming duplicates?
The loop gets you target file path and destination directory path.
The label :move
is called with each cycle of the loop and 1st
determines if the destination file not exist. If not exist, does
the move and exits the label. If does exist, uses another loop to
detect and trims the filename if it ends with (N)
where N
is
a number between 1 and 9. Then it enters another loop to move with
a destination filename with 1st available (N)
appended to the name.
Tested in root of D:\
. The output I get is:
D:\> main.cmd test
Prepared to test.
Press any key to continue . . .
1. move "D:\Main Folder\Folder2\Folder3a\File1.EXT" "D:\Main Folder\Folder2"
1 file(s) moved.
1. move "D:\Main Folder\Folder2\Folder3b\File2.EXT" "D:\Main Folder\Folder2"
1 file(s) moved.
1. move "D:\Main Folder\Folder2\Folder3c\File3.EXT" "D:\Main Folder\Folder2"
1 file(s) moved.
2. move "D:\Main Folder\Folder2\Folder3d\File1.EXT" "D:\Main Folder\Folder2\File1 (1).EXT"
1 file(s) moved.
1. move "D:\Main Folder\Folder3\Folder3a\File1.EXT" "D:\Main Folder\Folder3"
1 file(s) moved.
1. move "D:\Main Folder\Folder3\Folder3b\File2.EXT" "D:\Main Folder\Folder3"
1 file(s) moved.
1. move "D:\Main Folder\Folder3\Folder3c\File3.EXT" "D:\Main Folder\Folder3"
1 file(s) moved.
2. move "D:\Main Folder\Folder3\Folder3d\File1.EXT" "D:\Main Folder\Folder3\File1 (1).EXT"
1 file(s) moved.
As it shows, 2 files are moved with (1)
appended to the filename.
That is the lines starting with 2.
. Lines starting with 1.
have
moved with unmodified filenames.