使用 awk,根据第 2 列和第 5 列中的字符串以及第 3 列中的值计算行的平均值,并附加结果

Using awk, calculate average of rows based on string in 2nd and 5th column and value in 3rd column, and append result

这是

的变体

输入data.txt:

a;2016-04-25;10;2016-w17;2016-q2
b;2016-04-25;20;2016-w17;2016-q2
c;2016-04-25;30;2016-w17;2016-q2
d;2016-04-26;40;2016-w17;2016-q2
e;2016-07-25;50;2016-w30;2016-q3
f;2016-07-25;60;2016-w30;2016-q3
g;2016-07-25;70;2016-w30;2016-q3

求购output.txt:

a;2016-04-25;10;2016-w17;2016-q2;50
b;2016-04-25;20;2016-w17;2016-q2;50
c;2016-04-25;30;2016-w17;2016-q2;50
d;2016-04-26;40;2016-w17;2016-q2;50
e;2016-07-25;50;2016-w30;2016-q3;180
f;2016-07-25;60;2016-w30;2016-q3;180
g;2016-07-25;70;2016-w30;2016-q3;180

因此,计算有数据的天数的季度平均值并附加结果。

2016 年第二季度的平均值计算如下:

(10+20+30+40)/2 = 50     ("2" is the number_of_unique_dates for that quarter)

2016 年第 3 季度的平均值为:

(50+60+70)/1 = 180

这是我正在进行的工作,看起来非常接近最终解决方案, 但不确定如何获得 "number of unique dates"(第 2 列) 并用作除数?

awk '
BEGIN { FS=OFS=";" }
NR==FNR { s[]+=; next }
{ print [=14=],s[] / need_num_of_unique_dates_here }
 ' output.txt output.txt 

知道如何获得每个季度的 "number of unique dates" 吗?

$ cat tst.awk
BEGIN { FS=OFS=";" }
 != p5 { prt(); p5= }
{ lines[++numLines]=[=10=]; dates[]; sum+= }
END { prt() }
function prt(   lineNr) {
    for (lineNr=1; lineNr<=numLines; lineNr++) {
        print lines[lineNr], sum/length(dates)
    }
    delete dates
    numLines = sum = 0
}

$ awk -f tst.awk file
a;2016-04-25;10;2016-w17;2016-q2;50
b;2016-04-25;20;2016-w17;2016-q2;50
c;2016-04-25;30;2016-w17;2016-q2;50
d;2016-04-26;40;2016-w17;2016-q2;50
e;2016-07-25;50;2016-w30;2016-q3;125
f;2016-07-25;60;2016-w30;2016-q3;125
g;2016-07-25;70;2016-w30;2016-q3;125
h;2016-04-01;70;2016-w30;2016-q3;125

另一个gawk解决方案:

awk -F';' '{ a[][]+=; r[NR]=[=10=]; q[NR]= }
     END { 
           for (i in a) { s=0; len=length(a[i]); 
               for (j in a[i]) { s += a[i][j] } 
               a[i]["avg"] = s/len 
           } 
           for (n=1;n<=NR;n++) { print r[n],a[q[n]]["avg"] }
     }' OFS=";" file

输出:

a;2016-04-25;10;2016-w17;2016-q2,50
b;2016-04-25;20;2016-w17;2016-q2,50
c;2016-04-25;30;2016-w17;2016-q2,50
d;2016-04-26;40;2016-w17;2016-q2,50
e;2016-07-25;50;2016-w30;2016-q3,180
f;2016-07-25;60;2016-w30;2016-q3,180
g;2016-07-25;70;2016-w30;2016-q3,180

  • a[][]+= - 多维数组,汇总某个 季度

  • 内每个唯一日期的值
  • len=length(a[i]) - 确定某个季度内唯一日期的数量

  • for(j in a[i]){ s+=a[i][j] } - 将一个季度内所有日期的值相加

  • a[i]["avg"]=s/len - 计算平均值