这是基于 Juarez Rudsatz 的回答,非常感谢您为我指明了正确的方向。
虽然在 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 }
}
}'
}
这里的区别是最后一个块中的 substr,Juarez 示例在显示部分参数时添加了一个额外的 =。输出单个选项时也没有显示任何内容。
为了弥补额外的 = 我从 params==1 行中删除了 =%s。
为了弥补缺失的值,我几乎完全修改了 params==2 行。
我在匹配项中添加了排除;注释行也。
此示例将使用 INI 文件,例如
[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
要使用这个脚本,它与 Juarez 的示例没有什么不同。
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
这当然按预期运行。那么还有什么,是的,您可能想要一个函数文件来整理您的脚本,并且您可能想要访问这些值。这是一个简单的例子。
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.