Reputation: 4199
How do you escape quotes in a variable to compare with another one.
Example: A script outputs "The output of "test.exe" is OK" (without the surrounding quotes)
In a batch script I save the output in a variable in my batch script and then want to compare with a saved variable.
set ouputTest1 = "The output of "test.exe" is OK"
test.exe -p 75 > temp.txt
set /p TESTOUTPUT=< temp.txt
if %TESTOUTPUT% == %ouputTest1%
The problem is with the outputTest1 variable and the quotes in the string. I tried with double quotes like this:
set ouputTest1 = "The output of ""test.exe"" is OK"
But with no luck.
Any ideas?
Upvotes: 3
Views: 4068
Reputation: 82418
Your code has three problems:
The line of script, set ouputTest1 = "The output of "test.exe" is OK"
does not create a variable named outputTest1
; instead it creates a variable named outputTest1<space>
. This is the reason why %outputTest1%
will always be empty.
In a "set" statement, everything after the equal sign gets assigned--including the space and the outer quotes. In your case, the content of the variable winds up being <space>"The output of "test.exe" is OK"
.
Finally, you need to change your IF-compare. The correct way to do it is as follows:
set "ouputTest1=The output of "test.exe" is OK"
test.exe -p 75 > temp.txt
set /p TESTOUTPUT=< temp.txt
if "%TESTOUTPUT%" == "%ouputTest1%" echo Equal
Upvotes: 6
Reputation: 2341
The answer that wmz has proposed seems like a solid one, but I thought I could still offer this alternative, for consideration.
Instead of reading the output (i.e. your temp.txt) into a variable, for comparison, you could instead write out your comparison string to another file and compare the files. Something like the following:
echo The output of "test.exe" is OK>temp-expected.txt
fc temp.txt temp.expected.txt >NUL
if "%ERRORLEVEL%"=="0" ( echo YAY ) else ( echo BOO )
Upvotes: 1
Reputation: 3685
Using delayed expansion seem to get round this, with or without surrounding quotes (c
and d
are unquoted):
@echo off
setlocal disabledelayedexpansion
set a="The output of "test.exe" is OK"
set b="The output of "test.exe" is OK"
set "c=The output of "test.exe" is NOT OK"
set "d=The output of "test.exe" is NOT OK"
setlocal enabledelayedexpansion
if !a!==!b! echo a and b match!
if !c!==!d! echo c and d match!
endlocal
Upvotes: 4