Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape ampersands in variables - win batch

Tags:

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" 
like image 746
BearCode Avatar asked Jan 01 '13 05:01

BearCode


People also ask

How do I get out of the ampersand in CMD?

When working at the command line or with batch files, you must take one of two actions when you use strings that contain an ampersand. Either you must escape the ampersand by using the caret (^) symbol, or you must enclose the string inside quotation marks.

What does %% mean in batch?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

How do you escape a caret?

The first ^ is escaping the ^ character itself (the second ^ ) and the third ^ is escaping the & . When you run a command like ECHO ^& | MORE , the ^& is replaced with & by the shell before the output is piped to MORE .

How do I escape a character from a batch file?

In batch files, the percent sign may be "escaped" by using a double percent sign ( %% ). That way, a single percent sign will be used as literal within the command line, instead of being further interpreted.


1 Answers

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! 
like image 177
dbenham Avatar answered Oct 12 '22 15:10

dbenham