Matrix addition in awk

后端 未结 1 1798
长情又很酷
长情又很酷 2021-01-25 11:21

I have a bunch of variables which look like this:

(DURATION 1.57) + (DURATION 2.07)
(T0 10) (T1 0) (TX 0) + (T0 12) (T1 0) (TX 1)
(TC 1) (IG 0) + (TC 2) (IG 3)
<         


        
相关标签:
1条回答
  • 2021-01-25 12:07

    Here is one way to do it:

    awk '{
        gsub(/[()+]/, "")
        for(nf=1; nf<=NF; nf+=2) {
            flds[$nf] += $(nf+1)
        }
        sep = ""
        for(fld in flds) {
            printf "%s(%s %g)", sep, fld, flds[fld]
        sep = FS
        }
        print "";
        delete flds
    }' file
    (DURATION 3.64)
    (T0 22) (T1 0) (TX 1)
    (TC 3) (IG 3)
    
    • We remove the special characters ()+ using gsub() function.
    • We iterate over all fields adding variables to an array and adding the values
    • We iterate over the array, printing them in our desired format.
    • Add a new line after we are done printing
    • Delete the array so that we can re-use it on next line
    • Note: The order of lines will be same as input file but using the in operator for our for loop the variables on each line may appear in random order.
    0 讨论(0)
提交回复
热议问题