矩阵除了在AWK [英] Matrix addition in awk

查看:108
本文介绍了矩阵除了在AWK的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一大堆的变量,像这样:

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)

时有可能有awk的过程这使得结果是:

Is it possible to have awk process this such that the result is:

(DURATION 3.64)
(T0 22) (T1 0) (TX 1) 
(TC 3) (IG 3) 

或任何人可以推荐其他的UNIX程序,我可以用它来做到这一点?

Or can anyone recommend another unix program I can use to do this?

推荐答案

下面是做到这一点的一种方法:

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)


  • 我们删除特殊字符()+ 使用 GSUB()功能。

  • 我们迭代变量添加到一个数组中,并添加值的所有领域

  • 我们迭代这个数组,打印他们在我们需要的格式。

  • 添加新的生产线,我们完成打印后,

  • 删除阵列,使我们可以重新使用它的下一行

  • 注意:行的运营商对我们的循环的顺序是一样的输入文件,但使用 每行中的变量可能出现在随机顺序。

    • 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.
    • 这篇关于矩阵除了在AWK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆