Following is the first four records in a file “data.txt”.
71723 Ram Sen 70 72 75
91924 Raghubir Yadav 82 73 80
53425 Ram Chauhan 93 81 86
44917 Ratan Yadav 95 79 91
Each record contains ID(5 chars), 1 space, First name (10 chars),1 space, Second name (8 chars), 1space, marks in physics( 3chars), 1space, marks in chemistry(3 chars), 1space, marks in mathematics(3 chars) and a newline character.
Write a shell program info.sh to achieve the following
If the program is run without any argument (sh info.sh), it will display the first name, second name and average score of each student in the file.
If the program is run with numeric argument (sh info.sh 44917), it will assume it as ID of student and will output ID, first name, second name and the average score of that student. If ID does not match, the program should display “record not found”.
If the program is run with non-numeric
If the number of arguments is greater than one, the program should display an error message.
#!/bin/bash
if [[ $# -gt 1 ]]; then
echo "Too many arguments"
exit 1
fi
if [[ $# -eq 1 ]]; then
TARGET_ID=$1
[ "$TARGET_ID" -eq "$TARGET_ID" ] 2>/dev/null
if [ $? -ne 0 ]; then
echo "Argument must be a number"
exit 1
fi
grep -q "^$TARGET_ID " data.txt
if [ $? -ne 0 ]; then
echo "Record not found"
exit 1
fi
l=`grep "^$TARGET_ID " data.txt`
ID=${l:0:5}
name=${l:6:10}
surname=${l:16:8}
mark1=${l:25:3}
mark2=${l:29:3}
mark3=${l:33:3}
avg=$(( ($mark1+$mark2+$mark3)/3 ))
echo $name $surname $avg
else
cat data.txt | while read l; do
ID=${l:0:5}
name=${l:6:10}
surname=${l:16:8}
mark1=${l:25:3}
mark2=${l:29:3}
mark3=${l:33:3}
avg=$(( ($mark1+$mark2+$mark3)/3 ))
echo $name $surname $avg
done
fi
Comments
Leave a comment