Windows 批处理文件 - 拆分字符串以设置变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18820913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 10:53:06  来源:igfitidea点击:

Windows batch file - splitting a string to set variables

windowsfor-loopbatch-filedelimiter

提问by AndyC

I feel like I'm going around in circles with FOR loop options.

我觉得我在循环使用 FOR 循环选项。

I'm trying to take a string (output of a command) and split it on commas, then use each value to SET, e.g.

我正在尝试获取一个字符串(命令的输出)并将其拆分为逗号,然后使用每个值进行设置,例如

String: USER=Andy,IP=1.2.3.4,HOSTNAME=foobar,PORT=1234

细绳: USER=Andy,IP=1.2.3.4,HOSTNAME=foobar,PORT=1234

So I want to split on comma and then literally use that variable in SET. I don't know ahead of time how many many variables there will be.

所以我想用逗号分割,然后在 SET 中直接使用该变量。我提前不知道会有多少变数。

I've tried things like:

我试过这样的事情:

FOR %%L IN (%MYSTRING%) DO ECHO %%L

but that splits on the equals sign too so I end up with

但这也在等号上分裂,所以我最终得到

USER
Andy
IP
1.2.3.4

etc

等等

I just want to be able to do the following so I can SET USER=Andyetc, something like:

我只想能够执行以下操作,以便我可以SET USER=Andy等,例如:

FOR %%L IN (%MYSTRING%) DO SET %%L

What option or flags am I missing?

我缺少什么选项或标志?

回答by Aacini

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

普通FOR命令(无/F选项)中元素的默认分隔符是空格、制表符、逗号、分号和等号,并且无法修改,因此您可以使用FOR /F命令来解决这个问题:

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

解决此问题的另一种方法是首先获取变量名称,然后在常规 FOR 命令中为每对值执行赋值:

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%

回答by Marco Montel

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

如果您的输入类似于 HOSTNAME:PORT 并且您需要拆分为单独的变量,那么您可以使用它

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