This is based on Juarez Rudsatz answer, so thank you very much for setting me in the right direction.
I did have a little trouble with it though in Ubuntu 20.04 bash.
function parse_ini() {
cat /dev/stdin | awk -v section="$1" -v key="$2" '
BEGIN {
if (length(key) > 0) { params=2 }
else if (length(section) > 0) { params=1 }
else { params=0 }
}
match($0,/;/) { next }
match($0,/#/) { next }
match($0,/^\[(.+)\]$/){
current=substr($0, RSTART+1, RLENGTH-2)
found=current==section
if (params==0) { print current }
}
match($0,/(.+)=(.+)/) {
if (found) {
if (params==2 && key==substr($1, 0, length(key))) { print substr($0, length(key)+2) }
if (params==1) { printf "%s\n",$1,$3 }
}
}'
}
The differences here are the substr in the last block, Juarez example was adding an extra = when showing a sections parameters. It was also failing to show anything when outputting individual options.
To remedy the extra = I removed =%s from the params==1 line.
To remedy the missing values, I reworked the params==2 line almost completely.
I added in a match to exclude ; commented lines also.
This example will work with INI files such as
[default]
opt=1
option=option
option1=This is just another example
example=this wasn't working before
#commented=I will not be shown
;commentedtoo=Neither Will I.
[two]
opt='default' 'opt'just doesnt get me! but 'two' 'opt' does :)
iam=not just for show
To use this script it is no different to Juarez's example.
cat options.ini | parse_ini # Show Sections
cat options.ini | parse_ini 'default' # Show Options with values
cat options.ini | parse_ini 'default' 'option' # Show Option Value
cat options.ini | parse_ini 'two' 'iam' # Same as last but from another section
This ofcourse is functioning as expected. So what else, ah yes, you might want a functions file to declutter your script, and you probably want to access the values. Here is a quick example.
app="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)" # get the path to your program
source $app/functions.script # could be in a subdirectory.
somevar=$(cat $app/options.ini | parse_ini 'section' 'option') # Now its in a variable.
#!/bin/sh
is a POSIX sh script, not a bash script. That's an important distinction, becausesh
is missing features like arrays and maps (which bash calls "associative arrays") that are very useful in constructing this kind of things. – Viscountcyparse_ini_file()
and prints the desired value. The solutions usingsed
,awk
or any other shell utility are not reliable because they process lines and do not understand the structure of an ini file. – Nusku