Answer to Question #180399 in UNIX/Linux Programming for Ritesh

Question #180399

Consider a file “data.txt” which contains several records. Each record contains ID(7chars), 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 anewline character. Sample file content is as shown below:

71723 Ram    Sen    70 72 75

91924 Raghubir Yadav   82 73 80

53425 Ram    Chauhan 93 81 86

44917 Ratan   Yadav  95 79 91


ii) If the programis run with numeric argument ($./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”.


1
Expert's answer
2021-04-11T15:52:51-0400
#!/bin/bash

if [[ $# != 1 ]]; then
    echo "Usage: ./info.sh <ID>"
    exit 1
fi

sourceFile="data.txt" 

found=0

while IFS= read -r line
do
    id=${line:0:7}
    firstName=${line:8:10}
    secondName=${line:19:8}
    physicsMarks=${line:28:3}
    chemistryMarks=${line:32:3}
    mathematicsMarks=${line:36:3}

    avg=$(((${physicsMarks} + ${chemistryMarks} + ${mathematicsMarks}) / 3))

    if [[ $1 -eq ${id} ]]; then
        printf '%s %s %s %s\n' ${id} ${firstName} ${secondName} ${avg}
        found=1
        break
    fi

done < "$sourceFile"

if [[ ${found} == 0 ]]; then
    echo "record not found"
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