Search code examples
windowsbatch-filebatch-rename

Batch Script Loop through Array with Variable Index


Due to some operational needs, I am trying to write some simple batch script (hard code acceptable) which replace the filenames if it see some patterns, the replacement strings and the patterns are 1-1 mapping.

But I am stuck at the last step: For the Ren command, I could not access the arrays using variable counter. If I replace %counter% into integers like 2 or 3, the script works and can rename that specific file.

I am very new to batch script, may I know how can I access the array elements with variable index?

@ECHO OFF
Setlocal enabledelayedexpansion

Set "Pattern[0]=pat0"
Set "Pattern[1]=pat1"
...

Set "Replace[0]=rep0"
Set "Replace[1]=rep1"
...

Set /a counter = 0

For /r %%# in (*.pdf) Do (
    Set "File=%%~nx#"
    Ren "%%#" "!File:%Pattern[%counter%]%=%Replace[%counter%]%!"
    Set /a counter += 1
)

endlocal

Solution

  • Try like this with an additional for loop:

    @ECHO OFF
    Setlocal enabledelayedexpansion
    
    Set "Pattern[0]=pat0"
    Set "Pattern[1]=pat1"
    
    
    Set "Replace[0]=rep0"
    Set "Replace[1]=rep1"
    
    Set /a counter = 0
    
    For /r %%# in (*.pdf) Do (
        Set "File=%%~nx#"
        
        For /f "tokens=1,2 delims=;" %%A in ("!Pattern[%counter%]!;!Replace[%counter%]!") do (
            echo Ren "%%#" "!File:%%A=%%B!"
        )
        
        Set /a counter += 1
    )
    
    endlocal
    

    You can also try with additional subroutine or using CALL (see the Advanced usage : CALLing internal commands section and call set) but this should the best performing approach.