I found a bug in a bat file I was writing and by accident found a fix however I don’t understand why the fix worked.. Which is ultimately my question, or if there are other problems with this logic that I have not discovered.
The script does a line count in 2 or more files then the goal is to find the file with the lowest line count and later use that count in a variable later in the script as a parameter.
Example file 1 (9 lines):
Wrote,0
Wrote,1
Wrote,2
Wrote,3
Wrote,4
Wrote,5
Wrote,6
Wrote,7
Wrote,8
Example file 2 (10 lines):
Wrote,0
Wrote,1
Wrote,2
Wrote,3
Wrote,4
Wrote,5
Wrote,6
Wrote,7
Wrote,8
Wrote,9
The main difference that I see is that lines 9 & 10 in file 2 are two digit line numbers
NOTE: I am not referring to the actual value on each line but only the line number’s count value as my code does not try to parse the lines but only get the line count.
Near the top of the code I create then append the count values for each file into a temp file called ~numbers.txt so to simulate that process here assume my starting code is:
echo 9 > ~numbers.txt
echo 10 >> ~numbers.txt
type ~numbers.txt
So now I have a file with two lines “9” and “10” and of course 9 is lower than 10 but it also is one digit less than 10.
Now I attempt to find the lowest number contained in the file ~numbers.txt by reading the 1st line into a variable then looping and evaluating if current value is less than prior value.
setlocal enabledelayedexpansion
set /p lowest=<~numbers.txt
FOR /F "delims=" %%G in (~numbers.txt) DO IF %%G LSS !lowest! SET lowest=%%G
echo lowest num = %lowest%
When I run this code I get this output which is wrong:
lowest num = 10
What I have found is that if I remove the “delims=” from the FOR loop I will get the correct result of 9.
ALSO and what really screws up my understanding of the problem; If I only change the values in ~numbers.txt to 10 and 100 and leave the FOR loop line alone (keeping “delims=” ) then I get the correct value of 10 as my answer???
This is bad because it implies that my logic is flawed and that other number combinations will also yield different results.
Can anyone explain to me why this is the case and/or give an example on how to get the correct lowest number regardless of the values?
Thanks…
If you don’t see something it doesn’t mean it doesn’t exist. (I’m talking of spaces here)
Try this instead:
This will be truly WYSIWYG, no spaces at the end of line, no text comparisons by
ifbecause strings are not all numbers.Of course, stripping the spaces with default delims (one of which is a space) also works fine as you have noticed already.
Consider this way of determining lowest line count:
Note: no ifs, no delayed expansion