Parse .ini files with bash and sed

Written by Alexandre De Dommelin Wed Oct 19 18:41:31 UTC 2011

Here's a very cool way to parse ini files inside a shell script.
The following snippet will declare variables in the current scope of your script from all the key/values pairs present in the matching section.

#!/bin/bash
CONFIG_FILE="config.ini"
SECTION="section_1"

eval `sed -e 's/[[:space:]]*\=[[:space:]]*/=/g' \
    -e 's/;.*$//' \
    -e 's/[[:space:]]*$//' \
    -e 's/^[[:space:]]*//' \
    -e "s/^\(.*\)=\([^\"']*\)$/\1=\"\2\"/" \
   < $CONFIG_FILE \
    | sed -n -e "/^\[$SECTION\]/,/^\s*\[/{/^[^;].*\=.*/p;}"`

To remove confusion with the license covering my articles, this snippet is available under the WTFPL license.

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                    Version 2, December 2004

 Copyright (C) 2004 Sam Hocevar 

 Everyone is permitted to copy and distribute verbatim or modified
 copies of this license document, and changing it is allowed as long
 as the name is changed.

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. You just DO WHAT THE FUCK YOU WANT TO.

Written by | Permanent link | File under: Tips