@echo off
setlocal enabledelayedexpansion
set myvar=this=that=those
call :ReplaceSpecialChar1 myvar "=" "X"
echo Result of ReplaceSpecialChar1: [%myvar%]
set myvar=this=that=those
call :ReplaceSpecialChar2 myvar "=" "X"
echo Result of ReplaceSpecialChar2: [%myvar%]
REM More custom code ...
REM Only subroutines from here ...
goto :eof
REM Will only replace the first occurrence of the character to be replaced:
:ReplaceSpecialChar1
for /f "tokens=1* delims=%~2" %%a in ("!%1!") do (
if "%%b"=="" (set %1=%%a) else (set %1=%%a%~3%%b)
)
goto :eof
REM Will replace all occurrences of the character to be replaced:
:ReplaceSpecialChar2
set work=!%1!
set /a i = 0
:ReplaceLoop
if "!work:~%i%,1!"=="" (set %1=!work!&goto :eof)
if not "!work:~%i%,1!"=="%~2" (set /a i += 1&goto ReplaceLoop)
set head=!work:~0,%i%!
set /a i += 1
set work=!head!%~3!work:~%i%!
goto :ReplaceLoop
Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.
Have a better answer? Share it in a comment.
From novice to tech pro — start learning today.
There are two ways to work around this, but you may not like either :-).
First, if you know you are going to have to do this ahead of time, you could use a different character in the initial assignment in place of the = sign. Then, if you need to you can replace that character with either an = sign when you need it that way, or some other character, like an X in your example. Here's a small example:
Open in new window
Another approach that does require rebuilding the string, but isn't too painful is to use a FOR statement. Here's a simple example of that. Basically we let the FOR split the original string on the = sign, and then rebuild it with the desired character.Open in new window
~bp