views:

328

answers:

3

I'm trying to read a ini file with this format:

[SectionName]
total=4
[AnotherSectionName]
total=7
[OtherSectionName]
total=12

Basically I want to echo out certain values from the ini file(eg. the total under OtherSectionName followed by the total from AnotherSectionName).

A: 

Here is the document. Hope it helps!

mosg
that doesn't find different sections though does it?
Hintswen
A: 

Win32 api has set of function to deal with INI:

GetPrivateProfileInt

GetPrivateProfileSection

GetPrivateProfileSectionNames

GetPrivateProfileString

GetPrivateProfileStruct

GetProfileInt

GetProfileSection GetProfileString

(and symmetric writers) start there http://msdn.microsoft.com/en-us/library/ms724345(VS.85).aspx

Dewfy
+2  A: 

Here's a command file (ini.cmd) you can use to extract the relevant values:

@setlocal enableextensions enabledelayedexpansion
@echo off
set file=%1
set area=[%2]
set key=%3
set currarea=
for /f "delims=" %%a in (!file!) do (
    set ln=%%a
    if "x!ln:~0,1!"=="x[" (
        set currarea=!ln!
    ) else (
        for /f "tokens=1,2 delims==" %%b in ("!ln!") do (
            set currkey=%%b
            set currval=%%c
            if "x!area!"=="x!currarea!" if "x!key!"=="x!currkey!" (
                echo !currval!
            )
        )
    )
)
endlocal

And here's a transcript showing it in action (I've manually indented the output to make it easier to read):

c:\src>type ini.ini
    [SectionName]
    total=4
    [AnotherSectionName]
    total=7
    [OtherSectionName]
    total=12
c:\src>ini.cmd ini.ini SectionName total
    4
c:\src>ini.cmd ini.ini AnotherSectionName total
    7
c:\src>ini.cmd ini.ini OtherSectionName total
    12

To actually use this in another cmd file, just replace the echo %val% line below with whatever you want to do with it):

for /f "delims=" %%a in ('call ini.cmd ini.ini AnotherSectionName total') do (
    set val=%%a
)
echo %val%
paxdiablo