1

A very simple batch file. I'm trying to search for file extensions that are not .txt. There will be one .txt, but the rest will be like .txt_20190607.

for %%I in (\\01mtsdv130\Myapp\Log\*.*) do (
    set var1=%%~xI
    echo %var1
    if %var1%==".txt" ( 
       echo Matches
    ) else ( 
        echo does not match 
    )

)

I have files in that folder both .txt and those with the extra date info in the extension. What do I have wrong?

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Kathy Lori
  • 487
  • 6
  • 21

1 Answers1

1

There are two problems in the code.

The first one is that %-based expansion of normal variables is rather "static", in that it happens the first time code is parsed/executed and is fixed since then. That means that in iterations of the loop after the first, the result of %var1% will not change. You'd have to use !var1! (along with setting EnableDelayedExpansion) to get the behaviour you want.

An easier alternative is to get rid of var1 altogether and just use %%~xI.

The other problem is that CMD treats quotes (almost) as any other character. Most notably, the strings a and "a" are not considered equal. Therefore, the if should look like this:

if "%%~xI"==".txt" (
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • Thanks for the quick response Angew. This worked correctly if "%~xI"==".txt" ( , but if "%var1%"==".txt" ( did not, the comparison became "if "" ==".txt". – Kathy Lori Jul 09 '19 at 13:15
  • 1
    Quite the opposite, in batch files the `FOR` variables must be used with double percents `%%` dereferencing or otherwise. So the OP did that part right. The problem with code is `1.` Assigning and using a variable in the same code block by percent variable expansion `%var%`, which should use delayed expansion `!var!` if variable access can't be avoided and `2.` Mixing quoted and unquoted strings in comparison as you mentioned in your answer. So `if "%%~xI"==".txt"` would be correct. – sst Jul 09 '19 at 13:15
  • @sst Right you are, thanks for the correction. I was certain it was `%%` at declaration only, but apparently my memory tricked me (it's been some time since last I had to do this stuff). – Angew is no longer proud of SO Jul 09 '19 at 14:04