I am working on a batch file to loop through a list of strings (separated by commas) and remove them from the contents of a variable. However, I can't seem to get it working.
I was expecting for the varaible to have the strings removed from it, like so:
Lets say I have a list of a,b,c
and I wanted to detect and remove those characters from a variable, for example, set "var=abcd"
.
I want it to loop through the characters in the list and remove them from the variable:
set "var=%var:~a=%"
set "var=%var:~b=%"
set "var=%var:~c=%"
so the output would be:
> echo %var%
d
>
However, what I am getting is this using the code at the bottom:
> echo %var%
ECHO is off.
>
What is going on here? (I am fairly new to batch and I could not find anything that would help me)
My code:
@echo off
setlocal enabledelayedexpansion
@echo on
::Set the variable list, with '_' at the end to make the end of the items
set "varlist=a,b,c"
set varlist=%varlist%_
set "var="
set "string=acd"
::Loop through each character until ',' is found, then goto :var to remove it from the string
:loopvar
set ch=%varlist:~0,1%
set varlist=%varlist:~1%
if "%ch%"=="," goto var
set "var=%var%%ch%"
if "%varlist%"=="_" goto var
goto loopvar
::Remove from variable
:var
set "string=%string:~%var%=%"
set "var="
if "%varlist%"=="_" goto end
goto loopvar
::Display final result
:end
echo %var%
pause
Mmm... This is the way I would do it:
@echo off
setlocal EnableDelayedExpansion
rem Set the variable list, with ',' at the end to make the end of the items
set "varlist=a,b,c,"
set "string=acd"
set "p=%%"
set "var=%varlist:,=" & call set "string=!p!string:!var!=!p!" & set "var=%"
echo %string%
A detailed description of the method used appears at this thread. You can also remove the @echo off
line and carefully review the executed code, so you can grasp the magic... ;)