Monday 11 August 2008

Batch programming tip #16: Reading a property from an INI file

You are going to start thinking batch an I are having a love-hate relationship but there was an interesting question on computing.net recently. Someone asked how to get a property from an INI file and/or print things to an ini file or text file.

This was my effort at it.

File: - my.ini -

[provider]
name=ETH
organization=Stardust

[file]
server=192.168.254.42 ; use IP address
port=8080
file=wonderful.txt


The aim of the following batch is to retrieve the server IP address.
To do this we read all the lines of the ini file (that is each first "token" of every line, but because the property=value entities don't contain any default delimiters the first token will actually be the property=value pair on each line).

Then we try matching the beginning of the line with our property name.
If it matches, bingo, get the remaining string value and output it to ini/txt.

File: - ini_bat.bat -

@echo off
setlocal enabledelayedexpansion

:init_vars
:: this is our ini file path
set ini_file=my.ini
:: this is the key for which we want to retrieve a value
set key=server
:: this is the length of our key word (e.g. 'server')
set keylen=6
:: this is the index at which the equal sign should be
set /a eqsign=%keylen%+1
:: tmp dir name (should be empty)
set tmp_dir=tmp000
:: make temp dir
if not exist %tmp_dir% mkdir %tmp_dir%
goto get_key

:get_key
set tmp_file=%tmp_dir%\tmp.txt
:: this read the first token of every line, shouldn't be spaces in the ini file properties
for /F %%L in (%ini_file%) do (
set line=%%L
set linestart=!line:~0,%keylen%!

if !linestart!==%key% (
set value=!line:~%eqsign%!
goto output_value
)
)

:: this will erase existing %tmp_dir%\new.ini and %tmp_dir%\new.txt files

:output_value
echo Outputting value to ini file
echo server=%value% > %tmp_dir%\new.ini
echo Outputting value to text file
echo The value is: %value% > %tmp_dir%\new.txt
goto eof

:eof
echo Press any key to quit
pause > NUL
goto blackhole

:blackhole


And there you have it!

Some obvious improvements could be:
- setting the key dynamically (this also means computing the key length on the fly).
- including adequate behaviour if the property definitions include spaces
(e.g. server = 192.0.2.42)

Thoughts?

No comments:

Online Marketing
Add blog to our blog directory blog search directory Blog Directory Blogarama - The Blog Directory