0
User_Name=root;Password=1234;Server=192.168.1.49;DriverID=MySQL;Database=dbTest

How can i parse this string in batch-file. All samples about substrings are get X-to-Y.. But my string is dynamic.

I want to get between = and ; and set the variables:

username = root
password = 1234
server = 192.168.1.49
driverid = MySQL
database= dbTest

:~start,length notation is not fit for me.. Any other option ?

1
  • You mean user_name as a variable, right? Commented Mar 30, 2018 at 8:44

3 Answers 3

2
@ECHO OFF
SETLOCAL
SET "string=User_Name=root;Password=1234;Server=192.168.1.49;DriverID=MySQL;Database=dbTest"

FOR %%a IN ("%string:;=","%") DO SET %%a

SET

GOTO :EOF

You don't say where your string is stored, so I put it in string.

The string-substitution replaces each ; with "," so the command executed by the for id set "user_name=root","password... which is a valid but little-used application of the set command.

Sign up to request clarification or add additional context in comments.

Comments

1

If you know what the variables will be, then this modification of the method used in aschipfl's answer should suffice, (subject to reasonable characters):

Set "String=User_Name=root;Password=1234;Server=192.168.1.49;DriverID=MySQL;Database=dbTest"
Set "%String:;="&Set "%"&Set "String="
@Pause

I've left echoing on, so that you can see it in use,

Comments

0

What about replacing every ; by ";", enclosing the resulting string in between "", so you get "User_Name=root";"Password=1234";...? This can then be split by a standard for loop (no /F option!), because ; is a standard token separator for cmd just like SPACE, TAB, , and =. The latter is protected by the quotation marks. This is what I mean:

set "STRING=User_Name=root;Password=1234;Server=192.168.1.49;DriverID=MySQL;Database=dbTest"
set STRING="%STRING:;=";"%"
for %%I in (%STRING%) do set "$%%~I"
set $

I just prepended a $ sign to every variable name just for easier demonstration (set $ displays all of them); you may remove it, of course. Note that this approach fails in case the string contains wild-card characters like * or ?.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.