Batch Move and Rename already existing files

March 14, 2012 at 15:31:19
Specs: Windows XP
Pictures are uploaded on an hourly basis and needed to be deleted upon upload from the camera in which the camera is than again used by another employee but their pictures will than again have the same name as the previous employee and upon using the Move batch command it deletes the previous employees pictures

I am trying to move files from F:\Pics to C:\Pics and using the move command it replaces the existing files if they have the same name. What i need is a batch command that will search the C:\Pics folder for duplicate names and if it finds it to rename the file(s) for instance DSC001 if found will be renamed to DSC002 and if DSC002 is taken it will rename it DSC003 and so forth.


See More: Batch Move and Rename already existing files

Report •


#1
March 14, 2012 at 21:11:37
Try this:

cd /d F:\Pics
for %%i in (*.*) do 
  (set destfile=%%i
   if exist C:\Pics\destfile
     (:checknext
      set suffix=%destfile:~-3%
      set suffix=1%suffix%
      set /a suffix+=1
      set suffix=%suffix:~-3%
      if "%suffix%=="000"  goto overflow
      set destfile=DSC%suffix%
      if exist C:\Pics\%destfile%  goto checknext
     )
   move %%i C:\Pics\%destfile%
  )

The "overflow" label is for what you want to do when you run out of names. Numbers that begin with "0" are treated as octal (reason for prefixing suffix with 1).


Report •

#2
March 15, 2012 at 18:32:23
Run the batch file and nothing happens. No copy replace or rename

Report •

#3
March 15, 2012 at 19:37:02
Did you do any debugging to see what was not working? A word of caution: do not run this or any other batch file on good data until you are sure it is working as intended. I've added a tweak that should fix most problems, but you should set up a couple testing directories for debugging. Use a command like the following (with echo on) to log what happens:

MyBatch > batch.log

Then examine the log file to see if anything is unexpected. To narrow things down, you can add lines like the following to see if a variable is the value you expect.

echo destfile=!destfile!  suffix=!suffix!

Here is the tweaked batch to try (note "@echo off" is REM'd out for debugging):

REM @echo off
setlocal enabledelayedexpansion
cd /d F:\Pics
for %%i in (*.*) do 
  (set destfile=%%i
   if exist C:\Pics\destfile
     (:checknext
      set suffix=!destfile:~-3!
      set suffix=1!suffix!
      set /a suffix+=1
      set suffix=!suffix:~-3!
      if "!suffix!"=="000"  goto overflow
      set destfile=DSC!suffix!
      if exist C:\Pics\!destfile!  goto checknext
     )
   move %%i C:\Pics\!destfile!
  )
endlocal


Report •

Related Solutions


Ask Question