我有一堆不同类型的文件需要定期查看,它们的共同之处在于这些行有很多key=value类型的字符串.所以类似于:
Version=2 Len=17 Hello Var=Howdy Other
Run Code Online (Sandbox Code Playgroud)
我希望能够直接从awk中引用这些名称...所以类似于:
cat some_file | ... | awk '{print Var, $5}' # prints Howdy Other
Run Code Online (Sandbox Code Playgroud)
我怎么能这样做呢?
Win*_*ute 10
你可以得到的最接近的是将每个行的变量解析为关联数组.也就是说,
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 }'
Run Code Online (Sandbox Code Playgroud)
更可读:
{
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
}
Run Code Online (Sandbox Code Playgroud)
$ cat file | sed -r 's/[[:alnum:]]+=/\n&/g' | awk -F= '$1=="Var"{print $2}'
Howdy Other
Run Code Online (Sandbox Code Playgroud)
或者,避免无用地使用 cat:
$ sed -r 's/[[:alnum:]]+=/\n&/g' file | awk -F= '$1=="Var"{print $2}'
Howdy Other
Run Code Online (Sandbox Code Playgroud)
sed -r 's/[[:alnum:]]+=/\n&/g'
这会将每个键、值对放在自己的行上。
awk -F= '$1=="Var"{print $2}'
这会读取键值对。由于字段分隔符选择为=,因此键最终为字段 1,值作为字段 2。因此,我们只需查找第一个字段为 的行Var并打印相应的值。