use*_*525 8 windows parsing batch-file
我有以下字符串:
MyProject/Architecture=32bit,BuildType=Debug,OS=winpc
我希望能够获取值32bit,Debug和winpc并将它们存储在名为Architecture,BuildType和OS的变量中,以便稍后在批处理脚本中引用.我通常是一个Unix家伙,所以这对我来说是个新领域.任何帮助将不胜感激!
D.S*_*ley 27
这应该这样做:
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
Run Code Online (Sandbox Code Playgroud)
批处理FOR循环是一个非常有趣的机器.键入FOR /?在控制台的一些疯狂的东西它可以做一个说明.
这是一个有趣的解决方案,它不关心指定name = value对的数量或顺序.诀窍是用换行符替换每个逗号,以便FOR/F迭代每个name = value对.只要/字符串中只有一个,这应该可以工作.
@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%
Run Code Online (Sandbox Code Playgroud)
使用更多的代码,它可以有选择地只解析我们感兴趣的名称=值对.如果字符串中缺少变量,它还会将变量初始化为undefined.
@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!
Run Code Online (Sandbox Code Playgroud)