Parsing string in batch file

后端 未结 3 1021
萌比男神i
萌比男神i 2020-12-16 20:01

I have the following string:

MyProject/Architecture=32bit,BuildType=Debug,OS=winpc

I would like to be able to grab the values 32bit, Debug, and

3条回答
  •  萌比男神i
    2020-12-16 20:33

    Here is an interesting solution that doesn't care how many or what order the name=value pairs are specified. The trick is to replace each comma with a linefeed character so that FOR /F will iterate each name=value pair. This should work as long as there is only one / in the string.

    @echo off
    setlocal enableDelayedExpansion
    set "str=MyProject/Architecture=32bit,BuildType=Debug,OS=winpc"
    
    ::Eliminate the leading project info
    set "str=%str:*/=%"
    
    ::Define a variable containing a LineFeed character
    set LF=^
    
    
    ::The above 2 empty lines are critical - do not remove
    
    ::Parse and set the values
    for %%A in ("!LF!") do (
      for /f "eol== tokens=1* delims==" %%B in ("!str:,=%%~A!") do set "%%B=%%C"
    )
    
    ::Display the values
    echo Architecture=%Architecture%
    echo BuildType=%BuildType%
    echo OS=%OS%
    

    With a bit more code it can selectively parse out only name=value pairs that we are interested in. It also initializes the variables to undefined in case the variable is missing from the string.

    @echo off
    setlocal enableDelayedExpansion
    set "str=MyProject/Architecture=32bit,BuildType=Debug,OS=winpc"
    
    ::Eliminate the leading project info
    set "str=%str:*/=%"
    
    ::Define a variable containing a LineFeed character
    set LF=^
    
    
    ::The above 2 empty lines are critical - do not remove
    
    ::Define the variables we are interested in
    set "vars= Architecture BuildType OS "
    
    ::Clear any existing values
    for %%A in (%vars%) do set "%%A="
    
    ::Parse and conditionally set the values
    for %%A in ("!LF!") do (
      for /f "eol== tokens=1* delims==" %%B in ("!str:,=%%~A!") do (
        if !vars: %%B ! neq !vars! set "%%B=%%C"
      )
    )
    
    ::Display the values
    for %%A in (%vars%) do echo %%A=!%%A!
    

提交回复
热议问题