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|[email protected]
21PMR07123|John|012-3456789|[email protected]
21PMR07221|Amy|017-4567890|[email protected]
The user will need to enter the student ID to search the details. May I know how to check whether the student ID entered by the user is matched with the student ID in the text file and display the details of the student ID entered by the user?
Code for searching with student ID:
echo -n "Enter Student ID to search (eg: 21PMR12345): "
read studentID
The details of the student should be displayed as below:
Student ID: 21PMR07222
Name: Steven
Contact Number: 011-1234567
Email Address: [email protected]"
CodePudding user response:
One fairly direct option is to use awk
:
echo -n "Enter Student ID to search (eg: 21PMR12345): "
read studentID
awk -F'|' -v id="$studentID" '$1 == id { printf "Student ID: %s\nName: %s\nContact Number: %s\nEmail Address: %s\n", $1, $2, $3, $4 }' < student.txt
This will print any matching line (or lines) based on the input from the user matching exactly the StudentID from column 1 of student.txt. Here I'm asking awk to split each line of input based on the pipe symbol (|
) and also passing it the input from the user as awk variable "id". If column/field 1 ($1
) exactly matches the value of that variable, then we print the matching line with the required format.