user6242678
user6242678

Reputation:

Batch IF variable comparison mysteriously not working

I would like to create a batchfile which reads 2 different values and based on how they compare it proceeds accordingly. However, the comparison never works. The code is:

REM string1 and string2 contain the following test string "---------- COUNT.TXT 14" from which the number at the very right will be extracted in the next lines:
REM read numbers from strings and save as variables

set /a var1 =%:string1:~22,2%
set /a var2 =%:string2:~22,2%

IF #var1# == #var2# (
...
)

Any ideas on why the condition/comparison never works? "SET var" reveals both variables being equal (var1=14, var2=14), but nonetheless in the IF they are not recognized as such. Any guidance will be much appreciated!

The strings btw. are the second output line of a find /c (find and count).

Upvotes: 2

Views: 1006

Answers (3)

Stephan
Stephan

Reputation: 56180

It's IF %var1% == %var2% ... (not #) or to be sure: IF "%var1%" == "%var2%" ...

By the way: your string looks nearly like output from find /c If that's true, and the missing colon is just a typo, you can split your string with:

for /f "tokens=2 delims=:" %%i in ("%string1%") do set /a var1=%%i 

or even simpler:

set /a var1=%string1:*: =%

(remove from the beginning until (including) : (colon-space) (this wouldn't even need the /a)

No need to care, if it's two digits or one or six...

Upvotes: 2

user6242678
user6242678

Reputation:

REM string1 and string2 contain e.g. the following test string "---------- COUNT.TXT: 14" set /a var1=%string1:*: =% set /a var2=%string2:*: =% IF NOT "%var1%"=="%var2%" (echo not equal)

Summarizing suggestions this is how the working code looks like, special care should be taken to match the syntax including seemingly harmless spaces.

Upvotes: 0

dbenham
dbenham

Reputation: 130819

You have extra, unwanted colons in your assignment. The two lines should read as follows:

set /a var1 =%string1:~22,2%
set /a var2 =%string2:~22,2%

The space after the variable name is OK, but only when using SET /A. It would be good to get out of the habit of putting a space there so that the assignment works properly without the /a option.

The following creates variables with a space in the name - normally not a good idea:

set var1 =%string1:~22,2%
set var2 =%string2:~22,2%

So it is better to use

set /a var1=%string1:~22,2%
set /a var2=%string2:~22,2%

or

set var1=%string1:~22,2%
set var2=%string2:~22,2%

Upvotes: 1

Related Questions