Parse out key=value pairs into variables

后端 未结 5 1389
遇见更好的自我
遇见更好的自我 2020-11-27 21:37

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

5条回答
  •  感情败类
    2020-11-27 22:26

    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 }'
    

    More readably:

    {
      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
    }
    

提交回复
热议问题