tyee
tyee

Reputation: 331

for command to set a variable does not work

I'm running this command and I don't see why it won't work

setlocal EnableDelayedExpansion

for %%a in (harry-boy) do set %%a:-==

echo %harry%

pause

And this is the result I get -

e:\6\1>setlocal EnableDelayedExpansion

e:\6\1>for %a in (harry-boy) do set %a:-==

e:\6\1>set harry-boy:-==

e:\6\1>echo
ECHO is on.

e:\6\1>pause
Press any key to continue . . .

I'm changing the hyphen sign to a equals sign then running the set command on that. I expect to see that the variable "harry" = "boy"??

Here is a simple test -

set file=play=here.mkv
set %file:==-%
echo %file%
pause

and I get this -

set file=play=here.mkv
==-%
 was unexpected at this time.

set %file:==-%

I thought I would get the new contents of file = play-here.mkv. Ok, I see that this makes the syntax wrong and the set command stops. So how do I change the = to a hyphen?

Upvotes: 0

Views: 560

Answers (3)

Aacini
Aacini

Reputation: 67196

The string replacement format:

%var:old-string=new-string%

does NOT work on for replaceable parameters, just in Batch variables. The equivalent way for your example, using a variable instead, would be:

set a=harry-boy
set %a:-==%
echo %harry%
pause

Output:

C:>set a=harry-boy
C:>set harry=boy
C:>echo boy
boy
C:>pause
Press any key to continue . . .

Upvotes: 1

Magoo
Magoo

Reputation: 79982

SET will assign the value on the right of the first = to an environment variable named on the left.

Hence you would be assigning a value of = to a variable named harry-boy:- in BOTH cases.

You can verify this by executing

set harr

which will display any variable starting harr

Upvotes: 0

Monacraft
Monacraft

Reputation: 6630

Easy soloution:

for /f "tokens=1,2 delims=-" %%a in ("harry-boy") do set %%a=%%b
Echo %harry%

And that should do your job for you. But it will only work with one - in the quote.

Upvotes: 0

Related Questions