Search code examples
windowsbatch-filemovefile

Moving Files and Keeping Duplicates


I'm trying to move files and keep duplicate file names by appending (1) to one of the duplicate files.

I'm using

cd /D "source directory"
move *.JPG "target directory"

which doesn't solve the problem. Can someone please help?

Thank you for the assistance.


Solution

  • This should do what you want. We dir and search for all .jpg files in the source folder, then check if it exists, if it does, append a number using a counter, if it does not exist, we just move it..

    @echo off
    setlocal enabledelayedexpansion
    set "source=D:\source\"
    set "dest=D:\destination\"
    set /a cnt=0
    for /f "tokens=*" %%a in ('dir /S /B /A-D "%source%*.jpg"') do for /f "tokens=*" %%b in ('dir /B "%%a"') do if exist "%dest%\%%b" (
            set "ext=%%~xa"
            set "fname=%%~na"
            if exist "%dest%\!fname!(!cnt!)!ext!" (set /a cnt=!cnt!+1)
            set /a cnt=!cnt!+1
            move "%%a" "%dest%\!fname!(!cnt!)!ext!"
    ) else move "%%a" "%dest%\%%b"