BearCode
BearCode

Reputation: 2940

Escape ampersands in variables - win batch

I have a variable that contains ampersands and I need to create another variable that contains the first one. I know the "&" character can be escaped with carret (^) but I have no idea how to escape the text inside a variable.

set Name1 = Red ^& Green
set Name2 = %Name1% ^& Blue

'Green' is not recognized as an internal or external command, operable program or batch file.

I can't even "echo" the variables containing ampersands - I get the same error.

I need to use the variables in order to type their contents to the output or to manipulate files named by the variables like

type "%Name1%.txt"
type "%Name2%.txt"

Upvotes: 28

Views: 22245

Answers (4)

Jaroslav Záruba
Jaroslav Záruba

Reputation: 4876

The simplest solution would be this one:

for /f "delims= usebackq" %a in (`echo "First & ? * Last"`) do echo # %~a

...in a batch script:

for /f "delims= usebackq" %%a in (`echo "First & ? * Last"`) do echo # %%~a

or

for /f "delims= usebackq" %%a in (`echo "%~1"`) do echo # %%~a

Upvotes: -2

dbenham
dbenham

Reputation: 130809

The simplest solution is to use quotes for the assignment, and delayed expansion. This eliminates any need for escaping.

@echo off
setlocal enableDelayedExpansion
set "Name1=Red & Green"
set "Name2=!Name1! & Blue"
echo !Name2!

If you have a mixture of quoted and unquoted text, you sometimes must escape some characters. But that is only needed for the initial assignment. The content of a variable never needs to be escaped when using delayed expansion.

@echo off
setlocal enableDelayedExpansion
set var="This & that" ^& the other thing.
echo !var!

Upvotes: 26

MJZ
MJZ

Reputation: 1082

Two solutions come to mind, neither of which is sufficiently general, but they both "work":

  1. Always keep things in quotes and remove them when you need to, as noted in the previous solution.
  2. Re-quote the &'s: set name2=%name1:&=^&% ^& Blue

Upvotes: 0

David Ruhmann
David Ruhmann

Reputation: 11367

Unfortunately, you will have to double escape the ampersands since it is being evaluated twice or place the variable value in quotations.

set Name1=Red ^^^& Green
set Name2=%Name1% ^& Blue

But you will also need to add another set of escapes for when Name2 gets used. Which gets to be a major pain.

set Name1=Red ^^^^^& Green
set Name2=%Name1% ^^^& Blue

Or use quotations (Recommended)

set "Name1=Red ^& Green"
set "Name2=%Name1% ^& Blue"

Upvotes: 10

Related Questions