This could be a start:
awk -F'=' -v section="[efgh]" -v k="key1" '
$0==section{ f=1; next } # Enable a flag when the line is like your section
/\[/{ f=0; next } # For any lines with [ disable the flag
f && $1==k{ print $0 } # If flag is set and first field is the key print key=value
' ini.file
You pass two variables, section
and k
. section
needs to contain the section you want to look under. k
should contain the key
you are trying to obtain value for.
Find value of key1
under section [efgh]
:
$ awk -F'=' -v section="[efgh]" -v k="key1" '
$0==section{ f=1; next }
/\[/{ f=0; next }
f && $1==k{ print $0 }
' ini.file
key1=c
Find value of key2
under section [hijk]
:
$ awk -F'=' -v section="[hijk]" -v k="key2" '
$0==section{ f=1; next }
/\[/{ f=0; next }
f && $1==k{ print $0 }
' ini.file
key2=f