Reading an INI file and setting them as global variables in batch

梦想的初衷 提交于 2020-02-16 06:30:12

问题


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

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