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.
Advertisements. There are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command.
%%a refers to the name of the variable your for loop will write to. Quoted from for /? : FOR %variable IN (set) DO command [command-parameters] %variable Specifies a single letter replaceable parameter. (set) Specifies a set of one or more files. Wildcards may be used.
Please open a command prompt window, run set /? and read the output help. The syntax is set /P variable=prompt text or better set /P "password=Enter your password: " . And please note that variable password keeps its current value if already defined and user hits just RETURN or ENTER.
/r - iterate through the folder and all subfolders, i.e. recursively. %%I - placeholder for a path/filename. The above command simply lists all files in the current folder and all subfolders. Follow this answer to receive notifications.
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?
It seems you have called SETLOCAL EnableDelayedExpansion
somewhere higher in the code. Take a look here to see what the effects from that are.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With