Page 1 of 1

Batch renaming files

Posted: 02 Aug 2012 05:23
by Julya
Hello,
i have a list of files :
arch00.zip
arch01.zip
arch02.zip
arch03.zip
arch04.zip
and i want to rename arch01.zip in arch00.zip
arch02.zip in arch01.zip
arch03.zip in arch02.zip.
I want to to this in batch with a for.
How can i do it?
Thanks a lot in advance for help.

Re: Batch renaming files

Posted: 02 Aug 2012 05:56
by Squashman
if you already have a file named arch00.zip and arch01.zip, we have to do something with the arch00.zip file first if you want to rename arch01.zip to arch00.zip.

Re: Batch renaming files

Posted: 02 Aug 2012 06:03
by abc0502
this will rename this file arch00.zip to arch00_1.zip and then rename the others
I Didn't test it so make sure u test it in a copy of your files first

Code: Select all

@echo off
cls
Mode 50,10
setlocal enabledelayedexpansion
IF exist "arch00.zip" Ren "arch00.zip" "arch00_1.zip"
For /R %%z in (*.zip) Do (
   set file=%%~nz
   For /F "tokens=*" %%a in ("!file:~5!") Do (
      set num=%%a
      set /a Nnum = num - 1
   Ren "%%~nz.zip" "arch0!Nnum!.zip1" >nul
   )
   ) >nul
Ren "*.zip1" "*.zip" >nul
Exit /B

Re: Batch renaming files

Posted: 02 Aug 2012 06:20
by Squashman
I was trying to think what the user was possibly thinking and I assumed that the file names were also greater than 09 (arch10 arch11 etc). I didn't recurse the directory tree like abc0502 did. This would only work on a single folder and I don't have anything to take care of the initial 00 file but you could just use the same code abc0502 did to test for the existance of the 00 file and rename it.

Code: Select all

@echo off
setlocal enabledelayedexpansion
for %%G in (arch*.zip) do (
   set num=
   set base1=%~nG
   set base2=!base1:~0,-2!
   set ext=%~xG
   IF "!base1:~-2,1!"=="0" (
      set num=!base1:~-1!
   ) else (
      set num=!base1:~-2!
   )
   set /a num=!num! - 1
   IF !num! LSS 10 (
      rename "%%G" "!base2!0!num!!ext!"
   ) else (
      rename "%%G" "!base2!!num!!ext!"
)

Re: Batch renaming files

Posted: 02 Aug 2012 06:27
by abc0502
Good point Squashman, i missed the files that will exceed the 9th file

Re: Batch renaming files

Posted: 02 Aug 2012 06:47
by Squashman
abc0502 wrote:Good point Squashman, i missed the files that will exceed the 9th file

You did code per the example. I was just thinking out of the box. I should stop thinking! :lol:

Re: Batch renaming files

Posted: 02 Aug 2012 07:02
by abc0502
Infact you shouldn't, making a batch that work in general to work on any case is always better

Re: Batch renaming files

Posted: 02 Aug 2012 11:01
by Julya
Hi thanks a lot .I deleted Arhc00
if exist Arch00.zip del arch00.zip
and it worked.