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
.
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 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.
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.
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.
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%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With