Search code examples
windowsbatch-filefor-loopdelimiter

Batch How to treat dynamic FOR /F loop results with unknown amount of returned parameters


I have a function that works well in xp but fails in windows10 as i cant use the TAB as delimeter, only SPACE

setlocal EnableDelayedExpansion
...
CALL :myfunc VARtoSET KEY VALUE

:myfunc
FOR /F "usebackq skip=2 tokens=3 delims=    " %%A IN (`REG QUERY "%~2" /v "%~3"`) DO CALL SET "%~1=%%A"
goto :eof
...
endlocal

It returns correctly the data and expands possible variables like (CALL SET)

However if i try to use it on windows 10 ... it fails - seems like w10 doesnt like the literal TAB as i get absolutely no result using a literal TAB. If I remove the delimeter it becomes just a space (not a TAB and or SPACE as i read in some places) But I cannot use space as delimeter as the value or the data may contain a space itself and will ruin the purpose.


Solution

  • Ok, after dicovering that i wont get any TAB delimeters out of my reg query on w10 (xp does use TAB in output) i decided to solve this as follow

    We have a KEY_VALUE with possible whitespace (%3) We get a KEY_DATA result with possible whitespace (%1)

    In order to get the proper offset for out token of interest we count the elements of the KEY_VALUE passed to it, increase counter on elements

    :myfunc
    SET /A tk_offset=1
    FOR %%A IN (%~3) DO SET /A tk_offset+=1
    

    ignore the first returned parameter (%tk_offset%) that contains the DATA_TYPE and use (*) the rest as %%B

    FOR /F "skip=2 tokens=%tk_offset%,*" %%A IN ('REG QUERY "%~2" /v "%~3"') DO CALL SET "%~1=%%B"
    GOTO :eof
    

    We assign our result to %1 and expand possible variables using CALL SET

    Works on both winxp & win10