Back to C++
2026-05-038 min read

Bash Sort Lines (sort) (C++)

Learn Bash Sort Lines (sort) (C++) step by step with clear examples and exercises.

Why This Matters

Sorting lines of text files is a fundamental operation in many programming tasks. The ability to efficiently sort data can significantly improve the performance and readability of your code. In this lesson, we will discuss the sort command in Bash and its C++ equivalent, providing examples and explanations for each section.

Why This Matters

Understanding how to sort lines in text files is essential for many programming tasks. The sort command in Bash is a powerful tool for this purpose, but it's crucial to understand its limitations and how to use it effectively. Knowing the C++ equivalent of sort can help you write more efficient code when working with large amounts of data. Additionally, being familiar with sorting algorithms can be beneficial in interviews and real-world programming problems.

Prerequisites

To follow this lesson, you should have a basic understanding of:

  1. C++ syntax and programming concepts, such as variables, functions, loops, and arrays.
  2. Bash scripting basics, including command-line navigation, file handling, and shell scripts.
  3. Understanding of sorting algorithms, such as bubble sort, quicksort, and mergesort.
  4. Familiarity with STL (Standard Template Library) in C++.

Core Concept

Bash Sort Command

In Bash, the sort command is used to sort lines in a text file or output from another command. The syntax is as follows:

sort [OPTION]... [FILE]...

Here are some common options for the sort command:

  • -n: Sort numerically (ignores leading zeros and spaces).
  • -r: Reverse sort order.
  • -k NUM: Start sorting from the Nth column.
  • -o OUTPUT_FILE: Save sorted output to a file instead of stdout.
  • -t CHAR: Use CHAR as the delimiter between fields (default is whitespace).

C++ Sort Function

In C++, you can use the std::sort() function from the STL (Standard Template Library) to sort arrays or vectors. The syntax is as follows:

#include <algorithm>

void myFunction(int arr[], int n) {
std::sort(arr, arr + n);
}

In this example, myFunction sorts an array of integers using the std::sort() function.

Comparison Function

When working with custom data types or complex objects, you may need to provide a comparison function to std::sort(). This function should return true if the first argument is less than the second and false otherwise. Here's an example:

#include <algorithm>
#include <iostream>

struct Student {
std::string name;
int age;
};

bool compareStudents(const Student& a, const Student& b) {
if (a.age == b.age)
return a.name < b.name;
else
return a.age < b.age;
}

int main() {
std::vector<Student> students = {{"Alice", 20}, {"Bob", 19}, {"Charlie", 21}, {"David", 23}, {"Eve", 25}};
std::sort(students.begin(), students.end(), compareStudents);
for (const auto& student : students) {
std::cout << student.name << ", " << student.age << "\n";
}
return 0;
}

In this example, we define a Student struct and a comparison function to sort the vector of Student objects based on their age and name.

Sorting Custom Data Types with C++

When dealing with custom data types in C++, you may need to provide a custom comparison function to std::sort(). This function should return true if the first argument is less than the second and false otherwise. Here's an example:

#include <algorithm>
#include <iostream>
#include <vector>
#include <string>

struct Person {
std::string name;
int age;
};

bool comparePeople(const Person& a, const Person& b) {
if (a.age == b.age)
return a.name < b.name;
else
return a.age < b.age;
}

int main() {
std::vector<Person> people = {{"Alice", 20}, {"Bob", 19}, {"Charlie", 21}, {"David", 23}, {"Eve", 25}};
std::sort(people.begin(), people.end(), comparePeople);
for (const auto& person : people) {
std::cout << person.name << ", " << person.age << "\n";
}
return 0;
}

In this example, we define a Person struct and a comparison function to sort the vector of Person objects based on their age and name.

Worked Example

Let's consider a simple text file containing names and ages:

Alice 20
Bob 19
Charlie 21
David 23
Eve 25

To sort this file using Bash, you can run the following command:

sort -t ' ' -k 2 -o sorted.txt names_ages.txt

This command sorts the lines in names_ages.txt by the second column (age) and saves the sorted output to a file named sorted.txt. The resulting file should look like this:

David 23
Eve 25
Charlie 21
Alice 20
Bob 19

Now let's sort the same data using C++:

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

struct Person {
std::string name;
int age;
};

bool comparePeople(const Person& a, const Person& b) {
return a.age < b.age;
}

int main() {
std::vector<Person> people = {{"Alice", 20}, {"Bob", 19}, {"Charlie", 21}, {"David", 23}, {"Eve", 25}};
std::sort(people.begin(), people.end(), comparePeople);
for (const auto& person : people) {
std::cout << person.name << ", " << person.age << "\n";
}
return 0;
}

Compile and run this code, and you should see the same sorted output as the Bash example:

David, 23
Eve, 25
Charlie, 21
Alice, 20
Bob, 19

Common Mistakes

  1. Not understanding the sorting order: Remember that sort in Bash sorts lexicographically by default, and C++ sorts numerically when using std::sort(). If you have mixed data types or strings with non-numeric characters, you may need to provide a custom comparison function.
  2. Not handling special cases: Be aware of edge cases such as empty lines, leading/trailing whitespace, or non-numeric values in your input data. You may need to preprocess the data before sorting or add additional checks in your comparison function.
  3. Incorrect file paths: Ensure that you provide the correct file path when using sort in Bash and include the necessary header files when working with C++.
  4. Not compiling C++ code properly: Make sure to compile your C++ code using a compiler such as g++, and link it with the standard library (-lstdc++ or -lstlplus).
  5. Not providing a custom comparison function for custom data types: When working with custom data types in C++, you may need to provide a custom comparison function to std::sort(). Make sure your comparison function returns true if the first argument is less than the second and false otherwise.
  6. Incorrect delimiter when using Bash sort command: If your input file contains fields separated by a character other than whitespace, use the -t CHAR option with the sort command to specify the correct delimiter.

Practice Questions

  1. Write a Bash script that sorts lines in a file containing mixed uppercase and lowercase words alphabetically.
  2. Implement a C++ program to sort an array of strings using a custom comparison function based on the length of the strings.
  3. Given a text file with names and ages, write a Bash command to sort the data first by age and then by name for those with the same age.
  4. Write a C++ program to sort a vector of custom objects representing employees (name, department, salary) based on their salaries.
  5. Write a C++ program to sort an array of integers using a custom comparison function that prioritizes even numbers over odd numbers.
  6. Write a Bash script that sorts lines in a file containing IP addresses and sorts them based on the fourth octet (last number) first, then the third octet, and finally the first and second octets.
  7. Write a C++ program to sort a vector of custom objects representing students (name, GPA, major) based on their GPAs in descending order and majors in alphabetical order for students with the same GPA.

FAQ

  1. Why does my sorted output have extra spaces or lines?: Check for leading/trailing whitespace and empty lines in your input data. You may need to preprocess the data before sorting or add additional checks in your comparison function.
  2. How can I sort a file in reverse order using Bash?: Use the -r option with the sort command, as shown in the Core Concept section.
  3. Why is my C++ program not sorting correctly when dealing with custom data types?: You may need to provide a custom comparison function to std::sort(). Make sure your comparison function returns true if the first argument is less than the second and false otherwise.
  4. How can I sort a file in Bash based on multiple columns?: Use the -k NUM option with the sort command, specifying the column number to start sorting from. You can use multiple -k options to sort by multiple columns.
  5. Why is my C++ program not sorting custom data types correctly when dealing with objects that have different member variables?: Ensure that your comparison function compares all relevant member variables and returns the correct ordering.
  6. How can I sort a file in Bash based on a specific delimiter other than whitespace or a single character?: Use the -t CHAR option with the sort command to specify the delimiter, or preprocess the data to replace the delimiter with a single space before sorting.
  7. How can I sort a file in Bash based on a specific field within each line?: Use the awk command to extract the desired field and pipe the output to the sort command. For example, awk '{print $2}' names_ages.txt | sort -n.
  8. How can I sort an array of integers using a custom comparison function in C++ that prioritizes even numbers over odd numbers?: Define your comparison function to compare the modulus of each number and return true if the first argument has a smaller modulus or if they have the same modulus and the first argument is less than the second.
  9. How can I sort an array of integers using a custom comparison function in C++ that prioritizes odd numbers over even numbers?: Define your comparison function to compare the modulus of each number and return true if the first argument has a larger modulus or if they have the same modulus and the first argument is greater than the second.
  10. How can I sort an array of custom objects in C++ based on multiple criteria?: Define your comparison function to compare all relevant member variables in the desired order, prioritizing each criterion as needed. For example, if you want to sort students by GPA and then major, first compare GPAs and then majors.
Bash Sort Lines (sort) (C++) | C++ | XQA Learn