0

I have the following DOS commands in a batch file:

SET "REALM="
ECHO %REALM:/=.%

SET "REALM=Westeros"
ECHO %REALM:/=.%

SET "REALM=Westeros/"
ECHO %REALM:/=.%

The last two commands give me the expected results: Westeros Westeros.

But the first, replacing / for . on an empty variable, gives: /=.

Why does this happen and how can I do this right?

3
  • What is the "expected result" when you try to replace characters from a value that does not exists? Commented Sep 4, 2014 at 15:03
  • with an undefined %REALM%, ECHO %REALM:/=.% gives me %REALM:/=.% (as I would expect), not /=. (on cmd.exe; I have no DOS available any more) Commented Sep 4, 2014 at 16:49
  • I would expect the result to be "" or nothing. Commented Sep 5, 2014 at 7:21

2 Answers 2

3

It's a problem/feature of the parser with undefined variables.

How does the Windows Command Interpreter (CMD.EXE) parse scripts?

See also How does the Windows Command Interpreter (CMD.EXE) parse scripts?

To solve this you need to test first for undefined variables like.

set "REALM="
if defined REALM SET "REALM=%REALM:/=.%"
echo( %REALM%

I used here echo( to avoid the output of "ECHO IS OFF" when the variable is empty.

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

2 Comments

So, as I understand it, if REALM is undefined then the command-line processor will remove %REALM: from the command-line, leaving "/=." and continue the scan. Thus; To solve this puzzle I would have to define an empty variable, which I can't, to get the expected result.
Yes, replacing works only when the variable is defined, else it fails and you get rubbish
0

If you make aSET "REALM=". Then %Realm% is undefined (without any value).

1 Comment

I understand the variable is undefined, but why does the replace return /=. instead of an empty string or nothing?

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.