gpt4 book ai didi

bash - 将 key=value 对解析为变量

转载 作者:行者123 更新时间:2023-11-29 08:50:21 30 4
gpt4 key购买 nike

我有一堆不同类型的文件需要定期查看,它们的共同点是这些行都有一堆 key=value 类型的字符串。所以像这样:

Version=2 Len=17 Hello Var=Howdy Other

我希望能够直接从 awk 中引用名称...所以类似于:

cat some_file | ... | awk '{print Var, $5}' # prints Howdy Other

我该怎么做呢?

最佳答案

最接近的是每行首先将变量解析为关联数组。也就是说,

awk '{ delete vars; for(i = 1; i <= NF; ++i) { n = index($i, "="); if(n) { vars[substr($i, 1, n - 1)] = substr($i, n + 1) } } Var = vars["Var"] } { print Var, $5 }'

更具可读性:

{
delete vars; # clean up previous variable values
for(i = 1; i <= NF; ++i) { # walk through fields
n = index($i, "="); # search for =
if(n) { # if there is one:

# remember value by name. The reason I use
# substr over split is the possibility of
# something like Var=foo=bar=baz (that will
# be parsed into a variable Var with the
# value "foo=bar=baz" this way).
vars[substr($i, 1, n - 1)] = substr($i, n + 1)
}
}

# if you know precisely what variable names you expect to get, you can
# assign to them here:
Var = vars["Var"]
Version = vars["Version"]
Len = vars["Len"]
}
{
print Var, $5 # then use them in the rest of the code
}

关于bash - 将 key=value 对解析为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29108949/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com