Home > database >  How to iterate through items in an .ini file with a batch file?
How to iterate through items in an .ini file with a batch file?

Time:10-11

I am currently trying to loop through every item from a .ini file and to work with the values later on. But I can't figure out how. My config.ini file looks like this:

[items]
item_1=XXXXX
item_2=XXXXX
item_3=XXXXX
item_4=XXXXX

[SomeSection]
......

I found a way to iterate and echo every item from the config.ini file, like so:

@echo off 
for /F %%i in (config.ini) do (
   echo %%i
)

My problem is that I want to work with specific values. So I have to check the categorie and the keys from the config.ini file. I tried using this, but I ran into errors:

@echo off 
for /F %%i in (config.ini) do (
   SET item = %%i
   if %item%==[items] (
      rem do something here with the key and values now
   )
 )

As I already mentioned, I am not able to save the values to another variable, which leads to my problem that I can't work with them.

CodePudding user response:

A quite simple approach was to determine the line number of the target section header in advance, then skip such as many lines when reading the configuration file, stopping as soon as there occurs another string enclosed within brackets:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_CONFIG=%~dp0config.ini" & rem // (path to configuration file)
set "_SECT=items"             & rem // (section name without brackets)

rem // Clean up variables whose names begin with `$`:
for /F "delims==" %%V in ('set "$"') do set "%%V="
rem // Gather number of line containing the given section (ignoring case):
for /F "delims=:" %%N in ('findstr /N /I /X /C:"[%_SECT%]" "%_CONFIG%"') do set "SKIP=%%N"
rem // Read configuration file, skipping everything up to the section header:
for /F "usebackq skip=%SKIP% delims=" %%I in ("%_CONFIG%") do (
    rem // Leave loop as soon as another section header is reached:
    for /F "tokens=1* delims=[]" %%K in ("%%I") do if "[%%K]%%L"=="%%I" goto :NEXT
    rem // Do something with the key/value pair, like echoing it:
    echo(%%I
    rem // Assign a variable named of `$`   key and assign the value:
    set "$%%I"
)
:NEXT
rem // Return assigned variables:
set "$"

endlocal
exit /B

This script would assign the following variables, based on your sample configuration file:

$item_1=XXXXX
$item_2=XXXXX
$item_3=XXXXX
$item_4=XXXXX
  • Related