【问题标题】:Difference between %variable% and !variable! in batch file%variable% 和 !variable! 之间的区别!在批处理文件中
【发布时间】:2012-12-30 12:59:28
【问题描述】:

我正在编写一个批处理文件,我需要在其中输出一个包含“!”的字符串到另一个文件。但是当我将该字符串回显到另一个文件时,它会删除“!”从输出。

例如: 输入:

set LINE=Hi this is! output
echo !LINE!>>new_file.txt

new_file.txt 中的输出是:

Hi this is output

另外,如果输入是

set LINE=Hello!! this is output!!
echo !LINE!>>new_file.txt

new_file.txt 中的输出:

Hello

因此,它跳过了 ! (感叹号)从输出到 new_file。 如果我使用 %LINE%,那么它只会在输出文件中显示“echo is on”。

请提出解决此问题的方法。

【问题讨论】:

  • echo %LINE% 输出echo is on 时,你必须在一个块中。您应该添加更多代码
  • 这个问题很误导人,你不想知道区别,你想知道如何逃避它......

标签: windows command-line batch-file


【解决方案1】:

如果你开启了延迟扩展,想要输出感叹号,需要转义。

感叹号的转义不需要,一个或两个插入符号,具体取决于位置。

@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!

!var!%var% 在块中的区别在 DOS batch: Why are my set commands resulting in nothing getting stored? 进行了解释

批处理解析器的解释可以在How does the Windows Command Interpreter (CMD.EXE) parse scripts?找到

【讨论】:

  • 恕我直言,您的链接“为什么我的设置命令...”并不能完全解释 !var! %var% 之间的区别,而是需要 EnableDelayedExpansion。 NOI,但我认为 Magoo 在this question 上的回答更准确,因为它明确指出延迟扩展需要用于变量扩展的感叹号。仅设置 EnableDelayedExclamation 是不够的。对你来说可能是简单明了的批处理大师,但对我们来说是小虫子...... ;-)
【解决方案2】:

您似乎在代码的更高位置调用了SETLOCAL EnableDelayedExpansion。看看here 看看有什么效果。

【讨论】:

  • 谢谢你的回答。是的,我在我的文件中使用这个属性,因为这段代码在一个 for 循环中,而且我正在对这个字符串执行一些查找/替换操作,所以我必须使用它。
  • @User 我发送给你的链接很好地解释了它的副作用。我希望它能帮助您了解您所观察到的行为。
猜你喜欢
  • 2013-07-22
  • 2012-10-27
  • 1970-01-01
  • 2013-03-28
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
相关资源
最近更新 更多