问题
I have a batch file that does a bunch f things already and been trying to expand it to get some data from an ini file.
The ini file for example looks like this
[Settings1]
Text=Text
Text1=Text
Text2=Text
[Settings2]
Text=Text
Text1=Text
Text2=Text
I have figured out a way to get the section I require with the following batch
@echo off
setlocal EnableDelayedExpansion
set "file=settings.ini"
set "section=[Settings1]"
set flag=0
for /f "usebackq delims=" %%# in ("%file%") do (
set line=%%#
::trim
for /f "tokens=* delims= " %%a in ("!line!") do set "line=%%a"
set f=!line:~0,1!
if "!f!" neq ";" (
if !flag! equ 1 (
::for /f "tokens=1* delims==" %%a in ("!line!") do (
for /f "tokens=1* delims==" %%a in ("%%#") do (
set "!section!.%%a=%%b"
)
)
if "!f!" equ "[" (
if "!line!" equ "%section%" (
set flag=1
) else (
set flag=0
)
)
)
)
set %section%
This then outputs the following
Settings1.Text=Text
Settings1.Text1=Text
Settings1.Text2=Text
What I want to be able to do but cannot work out how to do is to take in each of these outputs and assign the value so just the 'Text' after the equals sign to its own variable that can then be recalled later in my script
回答1:
Have a look at the below example. I used your existing code, even though it can be improved. You can see how I utilized the for /l
loop to give you an idea of what can be done. You can shape this to fit your desired result. You can consider the same solution for different sections as well.
@echo off
setlocal enabledelayedexpansion
set "file=settings.ini"
set "section=[Settings1]"
set num=0
set flag=0
for /f "usebackq delims=" %%# in ("%file%") do (
set line=%%#
::trim
for /f "tokens=* delims= " %%a in ("!line!") do set "line=%%a"
set f=!line:~0,1!
if "!f!" neq ";" (
if !flag! equ 1 (
::for /f "tokens=1* delims==" %%a in ("!line!") do (
for /f "tokens=1* delims==" %%a in ("%%#") do (
set "!section!.%%a=%%b"
set /a num+=1
)
)
if "!f!" equ "[" (
if "!line!" equ "%section%" (
set flag=1
) else (
set flag=0
)
)
)
)
for /l %%a in (0,1,%num%) do (
if %%a equ 0 (
if defined [Settings1].Text echo(%[Settings1].Text%
) else (
if defined [Settings1].Text%%a echo(![Settings1].Text%%a!
)
)
来源:https://stackoverflow.com/questions/60170149/reading-an-ini-file-and-setting-them-as-global-variables-in-batch