bashawksedgrepini

Bash - parsing ini file, finding section name by values within


I have a config.ini file which looks like this (updated):

[group1]
base=100
hwadd=0x20
doorstatus=100
lock=101
bookingnr=010100
kode=1111
inuse=0

[group2]
base=100
hwadd=0x20
doorstatus=100
lock=102
bookingnr= 010101
kode=1111
inuse=0

[group3]
base=100
hwadd=0x20
doorstatus=100
lock=103
bookingnr=010103
kode=1111
inuse=0

[group4]
base=100
hwadd=0x20
doorstatus=100
lock=105
bookingnr=010105
kode=1111
inuse=0

[group5]
base=100
hwadd=0x20
doorstatus=100
lock=106
bookingnr=010106
kode=1111
inuse=0

[group6]
base=100
hwadd=0x20
doorstatus=100
lock=107
bookingnr=010107
kode=1111
inuse=0

[group7]
base=100
hwadd=0x21
doorstatus=100
lock=101
bookingnr=010108
kode=1111
inuse=0

[group8]
base=100
hwadd=0x21
doorstatus=100
lock=102
bookingnr=010109
kode=1111
inuse=0
...

I need to get the room number where 3 given values (base, hwadd, lock) match the script parameters. So lets say the bash script was called like this:

script.sh 100 0x20 105

the script would return 4 (since all 3 parameters match group4)

Finding a single value is a piece of cake

source config.ini

and every value is available under $valX but this is not parsing the section names so it is useless in this case..


Solution

  • You may use this awk:

    val='100 0x20 105'
    
    awk -F= -v vals="$val" 'BEGIN {
       n = split(vals, w, /[ \t]+/)
       for (i=1; i<=n; i++)
          values[w[i]] = 1
    }
    /^\[group[0-9]+]$/ {
       if (n == found)
          print grp
       delete seen
       found = 0
       grp = $0
       gsub(/^\[group|\]$/, "", grp)
    }
    NF == 2 && values[$2] && !seen[$2]++ {
       found++
    }
    END {
       if (n == found)
          print grp
    }' file
    

    4
    

    Code Demo