Last Updated: February 25, 2016
·
583
· auvinetke20

Shell + perl : Ini file parser

#!/bin/ksh

ini_parser()
{
    # Check if ini file exists
    if [ ! -f $1 ]; then
        echo "Erreur: le fichier a parser n'existe pas"
        return 0
    fi

    # Rewrite ini file in shell script 
    perl -lane 'if($_ =~ /^$/){$s="";next;}; if(m/^\[([^\]]+)\]$/g) { $s=$1;$s=~s/[^a-z0-9_]/_/g }; print $s.($s eq ""?"":"_").$_ if ($_ !~ m/^(\[|;)/ and $_ =~ m/^[^=]+=[^=]+/);print $s."=".$_, $s="" if($_ !~ m/^(\[|;)/ and $_ !~ m/^[^=]+=[^=]+/)' $1 >"${1}.tmp"

    # Call tmp shell script in bash
    . "${1}.tmp"

    # Remove tmp shell script after loading
    rm "${1}.tmp"
}