本文介绍了%variable% 和 !variable! 之间的区别在批处理文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

例如:输入:

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

new_file.txt 中的输出为:

Output in new_file.txt is:

Hi this is output

另外,如果输入是

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

new_file.txt 中的输出:

Output in new_file.txt:

Hello

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

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.

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

Please suggest a way to overcome this problem.

推荐答案

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

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!

!var!%var% 在块中的区别在 DOS 批处理:为什么我的设置命令导致没有存储任何内容?

The difference between !var! and %var% in blocks is explained at DOS batch: Why are my set commands resulting in nothing getting stored?

可以在 Windows 命令解释器 (CMD.EXE) 如何解析脚本?

这篇关于%variable% 和 !variable! 之间的区别在批处理文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:16