Windows批处理文件 - 拆分字符串设置变量 [英] Windows batch file - splitting a string to set variables

查看:413
本文介绍了Windows批处理文件 - 拆分字符串设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我兜兜转转与FOR循环选项。

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

我想取一个字符串(命令输出),并把它分解的逗号,然后用每一个值来设置,例如

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

字符串: USER =安迪,IP = 1.2.3.4,主机名= 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.

我试着喜欢的东西:

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

我只是想能够做到以下这样我就可以 SET USER =刘德华等,是这样的:

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

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

什么选项或标志我缺少什么?

What option or flags am I missing?

推荐答案

默认分隔符为纯元素命令(无/ F选项)的空格,制表符,逗号,分号和平等的迹象,也没有办法修改,所以您可以使用 FOR / F 命令这种方式解决这个问题:

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%

要解决这个问题的另一种方法是先取变量名,然后执行分配每对值的以规则FOR命令:

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%

这篇关于Windows批处理文件 - 拆分字符串设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆