Parsing ini files with sed
A while back I found this neat sed pipeline for extracting an ini file section into shell script variables:
INI_FILE=path/to/file.ini
INI_SECTION=TheSection
eval `sed -e 's/[[:space:]]*\=[[:space:]]*/=/g' \
-e 's/;.*$//' \
-e 's/[[:space:]]*$//' \
-e 's/^[[:space:]]*//' \
-e "s/^\(.*\)=\([^\"']*\)$/\1=\"\2\"/" \
< $INI_FILE \
| sed -n -e "/^\[$INI_SECTION\]/,/^\s*\[/{/^[^;].*\=.*/p;}"`
You now have variables in the scope of your shell script derived from the key/value pairs in that section of the ini script. REALLY handy. Thought it might help someone else if I recorded it here. I got it from this thread on debian-administration.org.NB: the eval is a ksh builtin. I imagine using declare in bash will achieve the same, but I haven't tested it.
NB2: it seems Solaris sed isn't quite up to the task - the above requires gnu sed.
05:07 PM, 08 Nov 2007 by Mark Aufflick Permalink | Short Link








Thank you ! Thank you ! Thank you !
Besides that it worked like charm ... Just one small hint :
One could separate the code from the configuration by :
# BEGIN parse-ini-file.sh # SET UP THE MINIMUM VARS FIRST INI_FILE=$0.$HOSTNAME.conf INI_SECTION=TheSection LOGFILE=$0.log wlog(){ test -z "$MYNAME" && MYNAME=`basename $0` logger -i -t "$MYNAME" -p "user.info" "`date +%Y.%m.%d-%H:%M:%S` $*" test -t 1 && echo "`date +%Y.%m.%d-%H:%M:%S` $*" test -z "$LOGFILE" || { echo "`date +%Y.%m.%d-%H:%M:%S` [$$] $*" >> $LOGFILE } } msg="Parse the ini file INI_FILE : $INI_FILE" wlog $msg eval `sed -e 's/[[:space:]]*\=[[:space:]]*/=/g' \ -e 's/;.*$//' \ -e 's/[[:space:]]*$//' \ -e 's/^[[:space:]]*//' \ -e "s/^\(.*\)=\([^\"']*\)$/\1=\"\2\"/" \ < $INI_FILE \ | sed -n -e "/^\[$INI_SECTION\]/,/^\s*\[/{/^[^;].*\=.*/p;}"` echo Var1 is $Var1 echo Var2 is $Var2 # END parse-ini-file.shby Unregistered Visitor on 11/09/11