awk bash avg calculation in file

夙愿已清 提交于 2021-02-11 14:41:49

问题


write the unix command to display roll, name and avg of all students whose score is more than 50 in each subject and average is more than or equal to 75.

avg can be calculated as (subj_1+subj_2)/2.

input:

roll ,name,subScore1,subScore2
123,a,88,78
101,b,76,90
812,c,78,98

output:

123 a 83
812 c 78

my code:

awk 'BEGIN {FS=',';OFS=' '} {if(NR>1 (&& $3>50 && $4>50) && ($3+$4)/2 >= 75){print $1,$2,($3+$4)/2}}' input_file

I don't know why I'm getting error. please help guys.


回答1:


EDIT: Adding more generic solution where OP's Input_file could have more than 4 fields/columns in that case one could try following.

awk '
BEGIN{
  FS=","
}
FNR==1{
  next
}
{
  for(i=3;i<=NF;i++){
    if($i>=50){
      ++count
    }
    sum+=$i
  }
  avg=(sum/count)
  if(count==(NF-2) && avg>=75){
    print $1,$2,avg
  }
  count=sum=avg=0
}
'   Input_file


Could you please try following, written and tested with shown samples with GNU awk.

awk '
BEGIN{
  FS=","
}
FNR==1{
  next
}
avg=($3+$4)/2
avg>=75 && ($3>=50 && $4>=50){
  print $1,$2,avg
}
'  Input_file


来源:https://stackoverflow.com/questions/62339294/awk-bash-avg-calculation-in-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!