Parse out key=value pairs into variables

后端 未结 5 1396
遇见更好的自我
遇见更好的自我 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:27

    I will try to explain you a very generic way to do this which you can adapt easily if you want to print out other stuff.

    Assume you have a string which has a format like this:

    key1=value1 key2=value2 key3=value3
    

    or more generic

    key1_fs2_value1_fs1_key2_fs2_value2_fs1_key3_fs2_value3

    With fs1 and fs2 two different field separators.

    You would like to make a selection or some operations with these values. To do this, the easiest is to store these in an associative array:

    array["key1"] => value1
    array["key2"] => value2
    array["key3"] => value3
    array["key1","full"] => "key1=value1"
    array["key2","full"] => "key2=value2"
    array["key3","full"] => "key3=value3"
    

    This can be done with the following function in awk:

    function str2map(str,fs1,fs2,map,   n,tmp) {
       n=split(str,map,fs1)
       for (;n>0;n--) { 
         split(map[n],tmp,fs2);
         map[tmp[1]]=tmp[2]; map[tmp[1],"full"]=map[n]
         delete map[n]
       }
    }
    

    So, after processing the string, you have the full flexibility to do operations in any way you like:

    awk '
        function str2map(str,fs1,fs2,map,   n,tmp) {
           n=split(str,map,fs1)
           for (;n>0;n--) { 
             split(map[n],tmp,fs2);
             map[tmp[1]]=tmp[2]; map[tmp[1],"full"]=map[n]
             delete map[n]
           }
        }
        { str2map($0," ","=",map) }
        { print map["Var","full"] }
       ' file
    

    The advantage of this method is that you can easily adapt your code to print any other key you are interested in, or even make selections based on this, example:

    (map["Version"] < 3) { print map["var"]/map["Len"] }
    

提交回复
热议问题