1

I have a large set files with names structured string_int_int_int_string.extension, and would like to batch rename them with left zero padding to 7 digits on the second int.

Example: rename stringA_1_2_3_stringB.jpg to stringA_1_0000002_3_stringB.jpg.

I've seen some helpful posts here, here, and here but haven't quite done it.

Here is what I have so far (not working, of course):

dir /b *.* >temp.txt

for /f "tokens=%%1,%%2,%%3,%%4,%%5 delims=_" %x in (temp.txt) do (
    setlocal enabledelayedexpansion
    set PAD=000000%%k
    set PAD=!PAD:~7!
    ren "%%i_%%j_%%k_%%l_%%m" %%i_%%j_%PAD%_%%l_%%m
)

I specifically want to do this with a batch file, not some other language or tool. (I'm aware of the various renaming tools out there.)

Any help is most welcome!

Community
  • 1
  • 1
user1205577
  • 2,388
  • 9
  • 35
  • 47

2 Answers2

2
setlocal EnableDelayedExpansion
dir /b *.* >temp.txt
for /F "tokens=1-5 delims=_" %%a in (temp.txt) do (
   set PAD=000000%%c
   set PAD=!PAD:~-7!
   ren "%%a_%%b_%%c_%%d_%%e"  "%%a_%%b_!PAD!_%%d_%%e"
)
Aacini
  • 65,180
  • 12
  • 72
  • 108
  • 1
    @user1205577: Insert an ECHO before the REN and report what is shown. Also, check that file names have the indicated format. – Aacini Nov 06 '12 at 21:03
  • @user1205577: DON'T DELETE older comments, because answers for them looks somewhat incoherent... Please, report if my solution correctly works (your deleted comment indicate that it does not, and you never clear this point). :( – Aacini Nov 08 '12 at 04:37
0

I use FINDSTR to filter out file names that don't match the specified pattern. A total of 4 tokens are needed - the first 3, followed by the rest of the file name.

@echo off
setlocal disableDelayedExpansion
for /f "tokens=1,2,3* delims=_" %%A in (
  'dir /b /a-d * ^|findstr /r "^[^_]*_[0-9]*_[0-9]*_[0-9]*_[^_]"'
) do (
  set "mid=%%C"
  set "pad=0000000%%C"
  set "start=%%A_%%B"
  set "end=%%D"
  setlocal enableDelayedExpansion
  echo ren "!start!_!mid!_!end!" "!start!_!pad:~-7!_!end!"
  endlocal
)
dbenham
  • 127,446
  • 28
  • 251
  • 390