user3450848
user3450848

Reputation: 23

Rename files with different extensions via Windows batch

I've spent two days on this and have looked at most every forum file I can find. Here's the scenario:

I have tens of thousands of image files: img_123.jpg, img_124.cr2, img_125.mov, etc. and I need them named: 64,001.jpg 64,002.cr2 64,003.mov and so on. Basically renaming the file while keeping the original extension in tact, while putting a comma in the thousands position.

Thanks to reading through the helpful Q&A's on Stack Overflow, I was able to write something that either A) renames the files serially but with no comma (64001.jpg 64002.cr2 64003.mov, etc.); or B) renames only the very first file for a unique type (img_123.jpg becomes 64,001.jpg just fine, while img_124.jpg img_125.jpg, etc. each fail with an error saying the filename is not unique.

Here's my code:

Upvotes: 1

Views: 204

Answers (2)

user3450848
user3450848

Reputation: 23

Here's what worked, thanks to Magoo for coming up with 95% of this.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=G:\ch\dos batch tests\# Projects\see if you can insert a coma"
SET /p num=enter the next higher image number here:  
FOR /f "delims=" %%a IN (
  'dir *.jpg *.cr2 *.mov /b /a-d "%sourcedir%\*.jpg *.cr2 *.mov" '
 ) DO (
 IF !num! lss 1000000 (
  SET "newname=!num:~0,-3!,!num:~-3!"
 ) ELSE (

  SET "newname=!num:~0,-6!,!num:~-6,3!,!num:~-3!"
 )
 REN "%sourcedir%\%%a" "!newname!%%~xa"
 SET /a num+=1
)

GOTO :EOF

Upvotes: 0

Magoo
Magoo

Reputation: 80203

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=c:\sourcedir"
SET /a num=64000
FOR /f "delims=" %%a IN (
  'dir /b /a-d "%sourcedir%\*" '
 ) DO (
 IF !num! lss 1000000 (
  SET "newname=!num:~0,-3!,!num:~-3!"
 ) ELSE (
  SET "newname=!num:~0,-6!,!num:~-6,3!,!num:~-3!"
 )
 ECHO REN "%sourcedir%\%%a" "!newname!%%~xa"
 SET /a num+=1
)

GOTO :EOF

All you'd need to do is set up sourcedir to suit your system.

The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO REN to REN to actually rename the files.

Upvotes: 1

Related Questions