Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

Hi this is output

Also, if input is

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

Output in 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.

Please suggest a way to overcome this problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
364 views
Welcome To Ask or Share your Answers For Others

1 Answer

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?

An explanation of the batch parser can be found at How does the Windows Command Interpreter (CMD.EXE) parse scripts?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...