将键=值对解析为变量 [英] Parse out key=value pairs into variables
本文介绍了将键=值对解析为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要定期查看一堆不同类型的文件,它们的共同点是这些行中有一堆key=value
类型的字符串.像这样:
I have a bunch of different kinds of files I need to look at periodically, and what they have in common is that the lines have a bunch of key=value
type strings. So something like:
Version=2 Len=17 Hello Var=Howdy Other
我希望能够直接从awk引用名称...类似这样:
I would like to be able to reference the names directly from awk... so something like:
cat some_file | ... | awk '{print Var, $5}' # prints Howdy Other
我该怎么做?
推荐答案
您可以获得的最接近的结果是,每行首先将变量解析为一个关联数组.也就是说,
The closest you can get is to parse the variables into an associative array first thing every line. That is to say,
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
}
这篇关于将键=值对解析为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文