0

I have my batch file which consists of the following command.

REN "H:\April2012\A04\mr_sudheendra_holla_vaderhobli.pdf.1335780379203.ver1" "mr_sudheendra_holla_vaderhobli.pdf"

But if duplicate files exist, the command will not execute. I would like my command to rename the file name to *(1).pdf and *(2).pdf etc. if there are duplicates. How can I do that?

user3427542
  • 89
  • 1
  • 3
  • 6
  • Please don't crosspost [Rename files using cmd and allow duplicates file name](https://superuser.com/q/849881) – DavidPostill Dec 08 '14 at 11:18
  • possible duplicate of [Windows batch file to copy and keep duplicates](http://stackoverflow.com/questions/5248393/windows-batch-file-to-copy-and-keep-duplicates) – DavidPostill Dec 08 '14 at 11:19
  • @DavidPostill - Definitely not a duplicate. REN is not the same as COPY, plus the technique used in the one and only answer would not work for this problem. – dbenham Dec 08 '14 at 13:04
  • @dbenham Not an exact duplicate, but rename is copy followed by delete ... so the dup answer is a starting point ... – DavidPostill Dec 08 '14 at 13:49
  • @DavidPostill - No, the "dup" answer is not a starting point because it assumes the target folder starts out empty. There could easily be name collisions if applied to rename. – dbenham Dec 08 '14 at 14:19
  • It's actually more a question of logic, than a question of coding. Obviously, if you want to switch 2 names, and both "exist" at all time, you can only solve that by giving one a temporary name. – tvCa Dec 08 '14 at 16:23

1 Answers1

2

renDup.bat

@echo off
setlocal disableDelayedExpansion
ren %1 %2 2>nul && echo %1 --^> "%~n2(%max%)%~x2"|| call :renDup %1 %2
exit /b

:renDup
set max=0
for /f "delims=" %%F in (
  'dir /b "%~dp1%~n2(*)%~x2" 2^>nul ^| findstr /ri "([1-9][0-9]*)\%~x2$"'
) do call :getMax "%%~nF"
set /a max+=1
ren %1 "%~n2(%max%)%~x2" && echo %1 --^> "%~n2(%max%)%~x2"
exit /b

:getMax
set "name=%~1"
set "name=%name:~0,-1%"
for %%N in ("%name:(=.%") do set num=%%~xN
set /a num=%num:~1%
if %num% gtr %max% set "max=%num%"
exit /b


usage:

renDup "H:\April2012\A04\mr_sudheendra_holla_vaderhobli.pdf.1335780379203.ver1" "mr_sudheendra_holla_vaderhobli.pdf"
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • This works great, however, I prefer `filename_012` over `filename(12)` and am unable to adjust your script accordingly. I think I figuered everything out but this: `("%name:(=.%")`. Could you please help me? :) – FatalBulletHit Jan 31 '18 at 02:38