bash – awk将key = value对解析为变量

前端之家收集整理的这篇文章主要介绍了bash – awk将key = value对解析为变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一堆不同类型的文件需要定期查看,它们的共同之处在于这些行有一堆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,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
}
原文链接:https://www.f2er.com/bash/385116.html

猜你在找的Bash相关文章