Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing string in batch file

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 winpc and store them in variables named Architecture, BuildType, and OS to reference later in the batch script. I'm normally a Unix guy so this is new territory for me. Any help would be greatly appreciated!

like image 444
user869525 Avatar asked Sep 27 '12 20:09

user869525


2 Answers

This should do it:

FOR /F "tokens=1-6 delims==," %%I IN ("MyProject/Architecture=32bit,BuildType=Debug,OS=winpc") DO (
    ECHO I %%I, J %%J, K %%K, L %%L, M %%M, N %%N
)
REM output is: I MyProject/Architecture, J 32bit, K BuildType, L Debug, M OS, N winpc

The batch FOR loop is a pretty interesting piece of machinery. Type FOR /? in a console for a description of some of the crazy stuff it can do.

like image 187
D.Shawley Avatar answered Oct 04 '22 02:10

D.Shawley


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!
like image 40
dbenham Avatar answered Oct 04 '22 02:10

dbenham