首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >%variable%和!variable之间的差异!在批处理文件中

%variable%和!variable之间的差异!在批处理文件中
EN

Stack Overflow用户
提问于 2013-01-16 16:58:48
回答 2查看 57K关注 0票数 32

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

例如:输入:

代码语言:javascript
复制
set LINE=Hi this is! output
echo !LINE!>>new_file.txt

new_file.txt中的输出为:

代码语言:javascript
复制
Hi this is output

另外,如果输入是

代码语言:javascript
复制
set LINE=Hello!! this is output!!
echo !LINE!>>new_file.txt

New_file.txt格式的输出:

代码语言:javascript
复制
Hello

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

请建议一种解决此问题的方法。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-16 17:46:06

如果您启用了延迟扩展并希望输出感叹号,则需要对其进行转义。

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

代码语言:javascript
复制
@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!

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

有关批处理解析器的说明,请参阅How does the Windows Command Interpreter (CMD.EXE) parse scripts?

票数 18
EN

Stack Overflow用户

发布于 2013-01-16 17:04:39

看起来你在代码中更高的地方调用了SETLOCAL EnableDelayedExpansion。看看here,看看它的效果是什么。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14354502

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档