我需要从具有典型结构的 ini 文件中检索键的值:
[abcd]
key1=a
key2=b
[efgh]
key1=c
key2=d
[hijk]
key1=e
key2=f
键名称在不同部分中重复,并且各部分没有一致的命名/顺序。我怎样才能从 efgh 中找到 key1 ?如果我 grep 那么我会找到所有 key1 (而且我不知道这些部分的顺序)。
我怀疑 sed 或 awk 可以做到这一点,但我找不到它......
这可能是一个开始:
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
and k
. section
需要包含您要查看的部分。k
应包含key
你正试图获得价值。
求值key1
下节[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
求值key2
下节[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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)