问题
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