Answer to Question #301163 in UNIX/Linux Programming for Sunitha

Question #301163

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.


1
Expert's answer
2022-02-23T12:19:14-0500
#!/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

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS