$cat empf
100,Smith James,80000,101 Ave N,San Francisco,CA
200,Lloyd Beth,80000,2010 University St,San Francisco,CA
300,Doe John,90000,1005 Royal Dr,Hartford,CT
400,Day Matt,85000,100 W 4th Ave,Seattle,WA
700,Bell Amy,60000,201 Winner CT,Atlanta,GA
800,Hawn Ruby,75000,120 Red Carpet Ln,Los Angeles,CA
While creating the script, it's required to keep "{" on the same line as BEGIN and END. The script errors out otherwise.NR is the inbuilt awk variable representing "Number of Records"
#!/usr/bin/awk
BEGIN{
FS=","
}
{
# sal $3 , name is $2
saltotal=saltotal+$3
}
END{
print "Number of Employees :", NR
print "Salary Total :", saltotal
print "Average Salary : ", saltotal/NR
}
Here's the output.$awk -f avgsal.awk empf
Number of Employees : 6
Salary Total : 470000
Average Salary : 78333.3
Optionally, we can pass the file separator on the command line instead of having a BEGIN block in the script.Note how awk automatically provides a float data type.