Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the first line of the command line is not taken for the output

sed '1d'|awk 'BEGIN{FS=";";sum=0} {sum+=$3; avg=sum/NR; if($3<avg) print $3}'

This is the unix command I tried for printing the salary of employees having salary less than the average salary of all the employees. The Input given was:

Empid;Empname;Salary
101;V;30000
102;A;45000
103;I;15000
104;S;40000

According to the input the average salary= 32500 which means 30000, 15000 both should be displayed in the output. But I can only get 15000 as my output. Please help and tell where am i going wrong.

like image 225
Vaishnavi Singh Avatar asked Mar 02 '23 02:03

Vaishnavi Singh


1 Answers

awk -F";" 'NR>1 {sum += s[++i] = $3}
    END {avg=sum/length(s); for (i=1;i in s;i++) if (s[i]<avg) print s[i]}' file
30000
15000

Also, no need to use both sed and awk for this. With awk you store all salaries, and at the END section you compare them with the average.

like image 50
thanasisp Avatar answered Mar 05 '23 15:03

thanasisp