Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows batch script to read an .ini file

I'm trying to read an .ini file with the following format:

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

Basically I want to print out certain values from the .ini file, for example the total under OtherSectionName followed by the total from AnotherSectionName.

like image 685
Hintswen Avatar asked May 19 '10 13:05

Hintswen


People also ask

Is .ini a batch file?

Batch file example:You will normally only want to use one command line with an . INI file per batch file, but there is nothing to prevent you from including as many as you like. They will all be processed one after another when you call the batch file.

How do I run a .ini file in Windows?

How to Open and Edit INI Files. It's not a common practice for people to open or edit INI files, but they can be opened and changed with any text editor. Just double-clicking it will automatically open it in the Notepad application in Windows.

Can a batch file read a text file?

Reading of files in a Batch Script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read. Since there is a no direct command to read text from a file into a variable, the 'for' loop needs to be used to serve this purpose.

What does %1 do in batch?

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.


1 Answers

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 "usebackq 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% 
like image 51
paxdiablo Avatar answered Sep 17 '22 21:09

paxdiablo