Windows batch file - splitting a string to set variables

半城伤御伤魂 提交于 2019-11-30 15:24:15
Aacini

The default delimiters for elements in plain FOR command (no /F option) are spaces, tab, commas, semicolons and equal signs, and there is no way to modify that, so you may use FOR /F command to solve this problem this way:

@echo off 

set MYSTRING=USER=Andy,IP=1.2.3.4,HOSTNAME=foobar,PORT=1234

:nextVar
   for /F "tokens=1* delims=," %%a in ("%MYSTRING%") do (
      set %%a
      set MYSTRING=%%b
   )
if defined MYSTRING goto nextVar
echo USER=%USER%, IP=%IP%, HOSTNAME=%HOSTNAME%, PORT=%PORT%

Another way to solve this problem is first taking the variable name and then executing the assignment for each pair of values in a regular FOR command:

setlocal EnableDelayedExpansion

set varName=
for %%a in (%MYSTRING%) do (
   if not defined varName (
      set varName=%%a
   ) else (
      set !varName!=%%a
      set varName=
   )
)
echo USER=%USER%, IP=%IP%, HOSTNAME=%HOSTNAME%, PORT=%PORT%

In case your input is something like HOSTNAME:PORT and you need to split into separate variables then you can use this

@echo off
set SERVER_HOST_PORT=10.0.2.15:8080


set SERVER_HOST_PORT=%SERVER_HOST_PORT::=,%

for /F "tokens=1* delims=," %%a in ("%SERVER_HOST_PORT%") do (
   set SERVER_HOST=%%a
   set SERVER_PORT=%%b
)

echo SERVER_HOST=%SERVER_HOST%
echo SERVER_PORT=%SERVER_PORT%
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!