1

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
shole
  • 4,046
  • 2
  • 29
  • 69
  • 1
    [Arrays, linked lists and other data structures in cmd.exe (batch) script](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) – Aacini Jun 24 '21 at 15:40

2 Answers2

2

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.

npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • Thanks for the reply! I tried it but it seems it always only execute the outer loop for one time. I tried to echo %counter% in outerloop and it only prints 0, never prints 1, 2 ..... – shole Jun 25 '21 at 04:14
  • 1
    @shole Ah. I see. But you figured it out :) – npocmaka Jun 25 '21 at 07:01
1

Based on @npocmaka's reply, I have further add a simple loop and finally it works for my case:

For /r %%# in (*.pdf) Do (
    Set "File=%%~nx#"
    For /l %%c in (0,1,8) Do (
        For /f "tokens=1,2 delims=;" %%A in ("!Pattern[%%c]!;!Replace[%%c]!") Do (
            Ren "%%#" "!File:%%A=%%B!"
            
        )
    )
    
)
shole
  • 4,046
  • 2
  • 29
  • 69