I currently have a text file called student.txt and there are some records in the text file.
The format of the records are StudentID|Name|ContactNumber|EmailAddress and the records are as follows:
21PMR07222|Steven|011-1234567|steven@yahoo.com
21PMR07123|John|012-3456789|john@yahoo.com
21PMR07221|Amy|017-4567890|amy@gmail.com
How to put the following code into if-else statement where if the student ID entered by user is matched with the student ID in the text file, the details of the student will be displayed, else error message "The student ID does not exist. Please enter again." will be displayed.
awk -F'|' -v id="$studentID" '$1 == id { printf "Name: %s\nContact Number: %s\nEmail Address: %s\n", $2, $3, $4 }' < student.txt
>Solution :
One idea:
awk -F'|' -v id="$studentID" '
$1 == id { found=1; printf "Name: %s\nContact Number: %s\nEmail Address: %s\n", $2, $3, $4 }
END { if (found==0) printf "The student ID does not exist. Please enter again." }
' student.txt
NOTES:
- this
awkcode is not going to prompt the user for a newstudentID - the parent code will need to be able to capture and parse the
awkoutput to determine if it should ask the user a new question; alternatively … - the
awkcode could return a non-0 status that the parent code could use to determine if the user should be prompted to enter a newstudentID
Have awk return a non-0 status code that the parent code can use for follow-on processing:
awk -F'|' -v id="$studentID" '
$1 == id { found=1
printf "Name: %s\nContact Number: %s\nEmail Address: %s\n", $2, $3, $4
}
END { if (found==0) {
printf "The student ID does not exist. Please enter again."
exit 1
}
}
' student.txt
awk_exit_status=$?
The default exit status of an awk script is 0 (ie, no issues). The END{...} block will generate an exit status of 1 if found==0.
The bash variable awk_exit_status will contain either a 0 (Name: ... Contact Number ... Email Address ...) or 1 (The student ID does not exist) which the parent bash script can then use to determine how to proceed.