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
1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 Ah. I see. But you figured it out :)
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!"
            
        )
    )
    
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.