Question

I have a variable that can contain string and/or number but in some case i have to remove numeric characters. So i am basicly;

if defined ARG2 (
    for %%b in (0 1 2 3 4 5 6 7 8 9) do set ARG2=!ARG2:%%b=!
)

It works almost all cases but there is a problem. If ARG2 contain nothing but numeric characters its changing ARG2 value to something like 9= . How can i fix this issue or is there a better way to remove numeric characters from variable?

Was it helpful?

Solution

When inputting 888 your for loop will reach 8 and remove all characters from the string. Therefore you have an empty variable. So when you try to remove 9 it expands to nothing, then for some reason (not entirely sure why) cmd doesn't consider the string manipulation, and just displays it (similarly 666 will output 7= and so on). To fix this you simply need to add a check, to see if ARG2 is empty or not.

if defined ARG2 (
    for %%b in (0 1 2 3 4 5 6 7 8 9) do if "!ARG2!"=="" ( goto :break ) else set ARG2=!ARG2:%%b=!
)
:break

This will just goto the :break label if ARG2 expands to nothing.

The answers here - How does the Windows Command Interpreter (CMD.EXE) parse scripts? - should give some better explanation of why.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top