Search code examples
batch-filedelayedvariableexpansion

Variable is not set


This is extension of the code from Why the loop is not running as expected?

Ultimately I want to read values from Report.txt (a comma separated file having values like 1,2,3,4 in a single line) and update these values in some fields of summary.yml (...field10 : var1, field11 :var2,... field25 :var3..) etc. For that I am trying to store values from Report.txt but the variable are not being set. Any help would be highly appreciated

@echo off
setlocal enableextensions disabledelayedexpansion

rem E:\Backups\ code   \  Hazard \ test1 \ it0 ... itn
rem             ^root     ^ %%X    ^ %%Y           ^ %%~dpc

for /D %%X in ("*") do for /D %%Y in ("%%~fX\*") do for /f "tokens=1,2,*" %%a in ('
    robocopy "%%~fY." "%%~fY." Report.txt /l /nocopy /is /s /nc /ns /ts /ndl /njh /njs 
    ^| sort /r 2^>nul
    ^| cmd /q /v /c "(set /p .=&echo(!.!)"
') do (

    copy "%%~fY\it0\summary.yml" "%%~dpc."

    setlocal enabledelayedexpansion
    set vidx=0
    for /F "tokens=1-4 delims=," %%A in (%%~dpc\Report.txt) do (
        set "var1=%%A"
        set "var2=%%B"
        set "var3=%%C"
        set "var4=%%D"
    )
    set var



    @echo  !var1!>  %%~dpc\temp.txt
    @echo  !var2!>> %%~dpc\temp.txt
    @echo  !var3!>> %%~dpc\temp.txt
    @echo  !var4!>> %%~dpc\temp.txt
)

Solution

  • Your for /f, with a tokens=* is reading the full line without splitting it.

    As the comma is a delimiter, you can split the line with a nested for loop

    setlocal enabledelayedexpansion
    for /F "tokens=*" %%A in (%%~dpc\Report.txt) do (
        for %%x in (%%A) do (
            SET /A "vidx=vidx + 1"
            set "var!vidx!=%%x"
        )
    )
    set var
    

    Or, to directly split using the for /f you need to indicate the tokens in the line that you need to retrieve

    for /F "tokens=1-4 delims=," %%A in (%%~dpc\Report.txt) do (
        set "var1=%%A"
        set "var2=%%B"
        set "var3=%%C"
        set "var4=%%D"
    )
    set var