Search code examples
windowsbatch-filebatch-rename

Not looping through all the files


Windows batch script: I have three files in a drectory.I`m trying to loop through the multiple files located in the directory and rename the files,but some how its not looping through. i can see that the var1 is getting the right file name but not for sub1.This in turn renames the other two files in the directory with wrong output. Could some one please help me on this.

@echo on & setlocal EnableDelayedExpansion 

set a=9
for /f "tokens=*" %%i in ('dir /b "C:\XX\YY\ZZ*"') do ( 
set var1=%%i
 SET sub1=%var1:~7,22%
 ECHO %sub1% 
  ren "%%i" "ABC!sub1!_!a!.dat" 
  set /a a+=1
) 

Solution

  • @echo on
    setlocal EnableDelayedExpansion 
    set a=10001 
    for /f "tokens=*" %%i in ('dir /b "C:\TEST\PBM\PAR*"') do ( 
    set var1=%%i
     SET sub1=!var1:~7,22!
     ECHO !sub1!
      ECHO ren "%%i" "ABC!sub1!_!a!.dat" 
      set /a a+=1
    )
    

    With delayedexpansion any reference to the value of a variable that is changed within the loop must use the !var! syntax. %var% will access the parse-time value.

    Note: REN is now echoed for verification.