Sorting Student Records by Multiple Fields
In this step, we'll sort a more complex student record that includes name, age, and grade. This is a common scenario when dealing with comprehensive student databases.
Let's first look at our data:
cat ~/project/student_records.txt
You'll see each line contains a student's name, age, and grade, separated by colons, like this:
David Lee:21:87
Alice Johnson:18:92
Charlie Brown:19:95
Bob Smith:20:88
Eve Wilson:18:91
To sort this file by age (second field) and then by grade (third field) if ages are the same, we'll use:
sort -t: -k2n -k3nr ~/project/student_records.txt
Here's what each part of the command means:
-t:
specifies that fields are separated by colons
-k2n
sorts based on the second field (age) numerically
-k3nr
then sorts based on the third field (grade) numerically in reverse order
This will display the student records sorted primarily by age (ascending) and secondarily by grade (descending) when ages are the same:
Alice Johnson:18:92
Eve Wilson:18:91
Charlie Brown:19:95
Bob Smith:20:88
David Lee:21:87
This type of multi-key sorting is extremely useful when you need to organize data based on multiple criteria. In this case, we're grouping students by age, and within each age group, we're ranking them by their grades.