简体   繁体   中英

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

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.

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 ('2^> nul 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM