How to replace multiple strings in for loop using the call command - replacing % is a problem

Viewed 65

Consider the following code:

@echo off
chcp 65001 >NUL

rem Main thread here which shows how to change each letter to UPPERCASE: https://stackoverflow.com/questions/34713621/batch-converting-variable-to-uppercase
rem Comment here: https://stackoverflow.com/a/34734724/8262102
rem I want to use this code to replace multiple strings but I'm having difficulty
rem with getting % replaced with double % symbols.

set "str=Change %% to double %% and replace other ^(And convert brackets^)"
echo %str% (Old variable)
call :VALIDATE str
echo %str% (New variable)
pause
goto :EOF

:VALIDATE
if not defined %~1 exit /b
for %%A in ("^%^%=^%^%^%^%" "(='('" ")=')'") do (
call set %~1=%%%~1:%%~A%%
)
goto :EOF

This is replacing the ( with '(' and the ) with ')'.

I cannot get % to be replaced with %%.

I've tried to escape the % by using both %% and ^% but no luck at this point in the code "^%^%=^%^%^%^%".

I'm out of ideas as to how to do this.

1 Answers

Does this help you at all?

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Set "str=Change %% to %%%%, and %%%% to %%%%%%%%, (and also enclose parentheses in single quotes)."
Echo %str%
Pause

SetLocal EnableDelayedExpansion
Set "str=!str:%%=%%%%!"
Set "str=!str:(='('!"
Set "str=!str:)=')'!"
EndLocal & Set "str=%str%"

Echo %str%
Pause

Or similarly:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Set "str=Change %% to %%%%, and %%%% to %%%%%%%%, (and also enclose parentheses in single quotes)."
Echo %str% (Old variable)
Call :Validate str
Echo %str% (New variable)
Pause
GoTo :EOF

:Validate
If "%~1" == "" Exit /B
SetLocal EnableDelayedExpansion
Set "_=!%~1!"
Set "_=!_:%%=%%%%!"
Set "_=!_:(='('!"
Set "_=!_:)=')'!"
EndLocal & Set "%~1=%_%"
Exit /B

[EDIT /]

And because …

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Set "str=Change %% to %%%%, and %%%% to %%%%%%%%, (and also enclose parentheses in single quotes)."
Echo %str% (Old variable)
Call :Validate str
Echo %str% (New variable)
Pause
GoTo :EOF

:Validate
If "%~1" == "" Exit /B
SetLocal EnableDelayedExpansion
Set "_=!%~1!"
For %%G In ("%%=%%%%" "(='('" ")=')'") Do Set "_=!_:%%~G!"
EndLocal & Set "%~1=%_%"
Exit /B
Related