Begin main content

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.

01:07 AM, 08 Nov 2007 by Mark Aufflick Permalink

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.sh

by Unregistered Visitor on 11/08/11

Error

The parser works fairly well, but there is a small error; it can cut short string values, such as: [section1] var="some text with a semicolon ; this parts gets erased" The part after the semicolon is simply removed.

by Unregistered Visitor on 01/16/13

Add comment