Home > Software engineering >  Batch file - extract value with delimiter from result containing spaces
Batch file - extract value with delimiter from result containing spaces

Time:12-29

I saw similar questions but none is related to my issue. I am using regedit to retrieve result where python is installed. I want to get this value:C:\Program Files\Python38\python.exe

C:\Users\user1>reg query HKLM\SOFTWARE\Python\PythonCore\3.8\InstallPath /V ExecutablePath

    HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\3.8\InstallPath
    ExecutablePath    REG_SZ    C:\Program Files\Python38\python.exe

Now I wrote a script:

SET PYTHON_PATH_SEARCH=reg query HKLM\SOFTWARE\Python\PythonCore\3.8\InstallPath /V ExecutablePath

FOR /F "tokens=1,2,3 delims= " %%A IN ('%PYTHON_PATH_SEARCH%') DO (
    CALL :set_python_path %%C

)
:set_python_path
SET PYTHON_PATH=%1
exit /B 0

But the result is: C:\Program The issue is that I am delimiting it using the spaces but I have a space in my desired output.

Thanks in advance~

CodePudding user response:

Use tokens=1,2,*

Token * is the remainder, after the highest nominated token number

AND call :set_... "%%C" Then %~1 in the subroutine.

Quoting combines a space-infused string into a single string.

~ removes the outer set of quotes from a metavariable.

Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. Don't assign " or a terminal \ or Space. Build pathnames from the elements - counterintuitively, it is likely to make the process easier

  • Related