Write a shell script, which gives back the average grade of a student The student name we should give as a parameter! If you give a name that is not in the data file, please write out an error message and write out the list of the names (Just the names without the grades!!!) as a help!
input file: class.txt
Mohammed 3 4 5 4
Alan 2 1 3 2
Li 3 5 1 3
Jane 4 2 3 1
SCRIPT:
#!/bin/bash# Variable Declaration
input_file="./class.txt"
name=$1
average=0
err_msg="\n\tPlease pass a student name to the script. \n\te.g.: ./average.sh Tom \n"
name_list=`cat class.txt | awk '(NR != 1) {print $1}' | tr "\n" "," | sed -e 's/,$//' -e 's/,/, /g' `
#---------------------------------------------------------------------------------------------
if [ -z "$name" ]
then
echo -e "$err_msg"
else
record=$(grep -w "$name" $input_file)
if [ -n "$record" ]
then
#sum=$(echo $a | awk '{sum=0; for (i=2; i<=NF; i++) { sum +=i} print sum }')
average=$(echo $record | awk '{sum=0; for (i=2; i<=NF; i++) { sum +=$i} print sum/(NF - 1) }')
echo -e "\t $name $average \n"
else
echo -e "No $name is in the list. There are: $name_list"
fi
fi
let's check the output: