在 Windows 批处理文件中转义符号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4087695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escaping ampersands in Windows batch files
提问by Bryan
I realise that you can escape ampersands in batch files using the hat character
我意识到您可以使用帽子字符在批处理文件中转义&符号
e.g.
例如
echo a ^& b
a & b
But I'm using the command
但我正在使用命令
for /f "tokens=*" %%A IN ('DIR /B /A-D /S .acl') DO ProcessACL.cmd "%%A"
which is finding all the files named '.acl' in the current directory, or a subdirectory of the current directory.
这是在当前目录或当前目录的子目录中查找所有名为 '.acl' 的文件。
The problem is, I'm finding path names that include the '&' character (and no, they can't be renamed), and I need a way of automatically escaping the ampersands and calling the second batch file with the escaped path as the parameter.
问题是,我正在查找包含“&”字符的路径名(不,它们不能重命名),我需要一种自动转义和号并使用转义路径调用第二个批处理文件的方法参数。
rem ProcessACL.cmd
echo %1
回答by jeb
The problem is not the escaping, it seems to be in the second script.
问题不在于转义,它似乎在第二个脚本中。
If there is a line like
如果有一条线
echo %1
Then it is expands and fails:
然后它扩展并失败:
echo You & me.acl
Better to use delayed expansion like
最好使用延迟扩展,如
setlocal EnableDelayedExpansion
set "var=%~1"
echo !var!
To avoid also problems with exclamation points !
in the parameter, the first set
should be used in a DisabledDelayedExpansion
context.
为了避免!
参数中的感叹号出现问题,第一个set
应该在DisabledDelayedExpansion
上下文中使用。
set "var=%~1"
setlocal EnableDelayedExpansion
echo !var!
回答by Tergiver
Your for line should be (note the *.acl)
您的 for 行应该是(注意 *.acl)
for /f "tokens=*" %%A IN ('DIR /B /A-D /S *.acl') DO ProcessACL.cmd "%%A"
ProcessACL.cmd can access the path passed to it with %1.
ProcessACL.cmd 可以访问使用 %1 传递给它的路径。
// ProcessACL.cmd
ECHO %1
Whatever is contained by the variable %1 is fully contained. There is no need for escapes. Escapes are for the batch processor to interpret the characters it is parsing.
变量 %1 包含的任何内容都被完全包含。没有必要逃避。转义用于批处理器来解释它正在解析的字符。