Monacraft
Monacraft

Reputation: 6620

Replacing "%" in a variable

Quite simple problem, no soloution yet:

C:\> Set var=^%test^%
C:\> Echo %var%
%test%

C:\> Echo %var:^%=-%
%test%

C:\> Why is this not producing -test-?

I tried doubling and removing the carrot(^) with little success. Any suggests (or solutions) appreciated.

Mona

Upvotes: 3

Views: 212

Answers (2)

cure
cure

Reputation: 2688

@echo off&setlocal enabledelayedexpansion
Set var=%%test%%
set a=var:%%=
echo var is %var%
echo var%%= is !%a%!

this should work... %% not ^% escapes %'s in batch files. in a batch file, ^% is really escaping the char after the %, in this case the newline.

Upvotes: 1

dbenham
dbenham

Reputation: 130839

The only way to replace % using SET search and replace is to use delayed expansion. It is impossible to escape the % in a way that lets you use normal expansion.

Rules for % are different in batch vs command prompt.

From within a batch script, % is escaped by doubling it:

@echo off
setlocal enableDelayedExpansion
set "var=%%test%%"
set var
set "var=!var:%%=-!"
set var

--OUTPUT--

var=%test%
var=-test-

From the command prompt, it is actually impossible to escape %. If text enclosed within quotes does not equal a variable name, then the percents are left in place. Also, an unpaired percent is also left in place. The code below assumes variable test does not exist:

C:\test>cmd /v:on
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\test>set "var=%test%"

C:\test>set var
var=%test%

C:\test>set "var=!var:%=-!"

C:\test>set var
var=-test-

C:\test>

If variable test does exist, then you can set your initial var value using something like:

c:\test>set "var=%^test%"
var=%test%

The caret "escapes" the next character, so it is consumed, leaving the correct value. It could be placed anywhere within the percents. But the code assumes variable ^test does not exist. If it did, then it would simply expand the value, as below:

C:\test>set "^test=Hello world"

C:\test>set ^^
^test=Hello world

C:\test>set "var=%^test%"

C:\test>set var
var=Hello world

C:\test>

Upvotes: 8

Related Questions