Average of multiple files without considering missing values

前端 未结 3 1701
野的像风
野的像风 2021-01-24 05:09

I want to calculate the average of 15 files:- ifile1.txt, ifile2.txt, ....., ifile15.txt. Number of columns and rows of each file are same. But some of them are missing values.

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-24 05:25

    Use this:

    paste ifile*.txt | awk '{n=f=0; for(i=1;i<=NF;i++){if($i*1){f++;n+=$i}}; print n/f}'
    
    • paste will show all files side by side
    • awk calculates the averages per line:
      • n=f=0; set the variables to 0.
      • for(i=1;i<=NF;i++) loop trough all the fields.
      • if($i*1) if the field contains a digit (multiplication by 1 will succeed).
      • f++;n+=$i increment f (number of fields with digits) and sum up n.
      • print n/f calculate n/f.

提交回复
热议问题