I am trying to find files with a specific date, but my equality isn't working as I think it is supposed to. Here is my batch file:
@echo off
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
chdir /d T:
FOR /r %%i IN (*) do (
echo %%i
set FileDate=%%~ti
echo Date: !FileDate!
set year=!FileDate:~6,4!
echo year: !year!
if !year! == 2009 (
echo is 2009
) else (
echo not 2009
)
)
And when I run it, I get the following output:
T:\SomeFile.txt
Date: 09/11/2009 02:51 PM
year: 2009
not 2009
Can somebody please explain to me why the year is printing as 2009, but is not being considered as 2009 by the if check? Thanks and sorry for my batch-file noobery.
Instead of the == comparison operator which means string comparison, you could use the EQU operator -- if you have the command extensions enabled (see if /? and also cmd /?):
if !year! EQU 2009
This does numeric comparison, so whitespaces around either of the values have no effect.
However, to avoid any whitespaces to become part of variable values (in this case year contains two trailing spaces), you should use the following syntax of set:
set "year=!FileDate:~6,4!"
Since the quotes "" are around the entire expression, they do not become part of the value.
It's actually a whitespace issue.
On this line you have additional whitespace at the end which is being added to the variable.
set year=!FileDate:~6,4!
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