Search code examples
parsingbatch-filefor-looptrim

Comparison of strings using variables always false (in Batch)


In my current folder, I have a file named backup(yyyy-mm-dd).7z
I need to keep that length variable even though here it is a constant.

@echo off
setlocal EnableDelayedExpansion

set "a=.\backup"
set "b=yyyy-mm-dd"
set "length=19"

for %%f in (.\*) do (

    set "fullpath=%%f"
    set "trimpath=!fullpath:~0,%length%!"

    set trimpath
    echo trimpath=%trimpath%

    if %trimpath% == %a%(%b% echo this is equal
)

I have 2 questions regarding that code:

  1. Why can I see the value of trimpath when I call set trimpath but not directly with %trimpath%?
  2. Why is my condition false? What should I do to get it true?

Solution

  • Here is the solution after following @foxidrive and @JosefZ advices!

    @echo off
    setlocal EnableDelayedExpansion
    
    set "a=.\backup"
    set "b=yyyy-mm-dd"
    set "length=19"
    
    for %%f in (.\*) do (
    
        set "fullpath=%%f"
        set "trimpath=!fullpath:~0,%length%!"
    
        echo trimpath=!trimpath!
    
        if "!trimpath!" == "%a%(%b%" echo this is equal
    )
    

    If you need to test the solution, just create a file named backup(yyyy-mm-dd) in your current folder.