windows %variable% 和 !variable! 之间的区别 在批处理文件中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14354502/
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
Difference between %variable% and !variable! in batch file
提问by Vishal
I am writing a batch file where I need to output a string containing '!' to another file. But when I echo that string to another file, it removes "!" from the output.
我正在编写一个批处理文件,我需要在其中输出一个包含 '!' 的字符串。到另一个文件。但是当我将该字符串回显到另一个文件时,它会删除“!” 从输出。
Eg: Input:
例如:输入:
set LINE=Hi this is! output
echo !LINE!>>new_file.txt
Output in new_file.txt is:
new_file.txt 中的输出是:
Hi this is output
Also, if input is
另外,如果输入是
set LINE=Hello!! this is output!!
echo !LINE!>>new_file.txt
Output in new_file.txt:
new_file.txt 中的输出:
Hello
Hence, it skips the ! (Exclamation mark) from the output to the new_file. If I use %LINE%, then it simply displays "echo is on" to the output file.
因此,它跳过了 ! (感叹号)从输出到 new_file。如果我使用 %LINE%,那么它只会在输出文件中显示“echo is on”。
Please suggest a way to overcome this problem.
请提出一种克服这个问题的方法。
采纳答案by jeb
If you have delayed expansion enabled and want to output an exclamation mark, you need to escape it.
如果您启用了延迟扩展并希望输出感叹号,则需要对其进行转义。
Escaping of exclamation marks needs none, one or two carets, depending on the placement.
感叹号的转义不需要,一个或两个插入符号,具体取决于位置。
@echo off
REM No escaping required, if delayed expansion is disabled
set test1=Test1!
setlocal EnableDelayedExpansion
REM One caret required
REM Delayed expansion uses carets independent of quotes to escape the exclamation mark
set "test2=Test2^!"
REM Two carets required
REM The first caret escapes the second caret in phase2 of the parser
REM Later in the delayed expansion phase, the remaining caret escapes the exclamation mark
set test3=Test3^^!
echo !test1!
echo !test2!
echo !test3!
The difference between !var!
and %var%
in blocks is explained at DOS batch: Why are my set commands resulting in nothing getting stored?
DOS批处理中解释了块!var!
和%var%
块之间的区别:为什么我的设置命令导致没有存储任何内容?
An explanation of the batch parser can be found at How does the Windows Command Interpreter (CMD.EXE) parse scripts?
批处理解析器的解释可以在 Windows 命令解释器 (CMD.EXE) 如何解析脚本中找到?