从ini文件的某些部分读取某些密钥(sed/awk?) [英] Read certain key from certain section of ini file (sed/awk ?)
问题描述
我需要从具有典型结构的ini文件中检索键的值:
I need to retrieve the value of a key from an ini file with typical structure:
[abcd]
key1=a
key2=b
[efgh]
key1=c
key2=d
[hijk]
key1=e
key2=f
,键名在不同的部分重复,并且各部分没有一致的命名/顺序.如何从efgh中找到key1?如果我grep,那么我会找到所有key1(并且我不知道各节的顺序).
with key names repeated in different sections, and no consistant naming/order of sections. How could I find key1 from efgh? If I grep then I'll find all key1's (and I don't know the order of the sections).
我怀疑sed或awk可以做到这一点,但我找不到它...
I suspect sed or awk can do this but I can't find it...
推荐答案
这可能是一个开始:
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
您传递两个变量section
和k
. section
需要包含要查看的部分. k
应该包含您要为其获取值的key
.
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.
在[efgh]
部分下找到key1
的值:
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
在[hijk]
部分下找到key2
的值:
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
这篇关于从ini文件的某些部分读取某些密钥(sed/awk?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!