9

我有以下字符串:

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

我希望能够获取 32bit、Debug 和 winpc 的值,并将它们存储在名为 Architecture、BuildType 和 OS 的变量中,以便稍后在批处理脚本中引用。我通常是一个 Unix 人,所以这对我来说是一个新领域。任何帮助将不胜感激!

4

3 回答 3

30

这应该这样做:

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

批处理FOR循环是一个非常有趣的机器。输入FOR /?一个控制台来描述它可以做的一些疯狂的事情。

于 2012-09-27T20:57:53.077 回答
8

这是一个有趣的解决方案,它不关心 name=value 对指定的数量或顺序。诀窍是用换行符替换每个逗号,以便 FOR /F 将迭代每个名称=值对。只要/字符串中只有一个,这应该可以工作。

@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%

使用更多代码,它可以选择性地仅解析出我们感兴趣的名称=值对。它还将变量初始化为未定义,以防字符串中缺少变量。

@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!
于 2012-09-27T22:17:11.297 回答
3

尝试以下操作:

@ECHO OFF

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

FOR /F "tokens=1,2,3 delims=," %%A IN ("%Var%") DO (
    FOR /F "tokens=1,2 delims==" %%D IN ("%%A") DO (
        SET Architecture=%%E
    )
    FOR /F "tokens=1,2 delims==" %%D IN ("%%B") DO (
        SET BuildType=%%E
    )
    FOR /F "tokens=1,2 delims==" %%D IN ("%%C") DO (
        SET OS=%%E
    )
)

ECHO %Architecture%
ECHO %BuildType%
ECHO %OS%

PAUSE
于 2012-09-27T20:58:08.990 回答