转义符号中的转义符-赢批 [英] Escape ampersands in variables - win batch
问题描述
我有一个包含与号的变量,我需要创建另一个包含第一个的变量.我知道&"字符可以用carret(^)进行转义,但是我有不知道如何在变量内转义文本.
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
绿色"未被识别为内部或外部命令,可操作程序或批处理文件.
我什至无法回显"包含&"符号的变量-我遇到了同样的错误.
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"
推荐答案
最简单的解决方案是对引用使用引号,并延迟扩展.这样就无需进行转义.
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!
这篇关于转义符号中的转义符-赢批的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!