sort Command in Linux
Overview
The sort command in Linux is a versatile utility that sorts lines of text from standard input or a file. It is useful for organizing, analyzing, and filtering data in files. The command offers various options to customize the sorting process, such as sorting by numerical values, month names, or case-insensitive.
Transform Your Career
Choose from our industry-leading programs designed for career success
Modern Software and AI Engineering Program
Master full-stack development with AI integration
+1000 moreModern Data Science and ML with specialisation in AI
Advanced data science techniques with AI specialization
+1000 moreAdvanced AIML with Specialisation in Agentic AI
Deep dive into AIML with focus on Agentic systems
+1000 moreDevOps, Cloud & AI Platform Engineering
Build and manage AI-powered cloud infrastructure
+1000 moreAI Engineering Advanced Certification by IIT-Roorkee
Premier AI engineering certification from IIT-Roorkee
Linux sort Command Syntax
The syntax for the sort command is as follows:
Where:
- OPTION: Flags that modify the sorting behavior of the command. Multiple options can be combined.
- FILE: The input file(s) to be sorted. If no file is provided, the command reads from standard input.
sort Command Options:
- -b: Ignore leading blanks (spaces and tabs) when determining sort keys.
- -c: Check if the input is already sorted and output any unsorted lines.
- -f: Perform case-insensitive sorting.
- -n: Sort numerically.
Example Usages
-
Sort a file alphabetically:
Output:
Explanation: This command sorts the lines in file.txt alphabetically and displays the output.
-
Sort a file numerically:
Output:
Explanation: This command sorts the lines in numbers.txt numerically and displays the output.
Turn Learning into Career Growth
Tips
-
To sort in reverse order, use the -r option.
-
To sort by a specific column, use the -k option.
Advanced Use Cases of sort Command in Linux
-
Sort by the second column numerically:
Output:
Explanation: This command sorts the lines in file.txt based on the second column's numeric values and displays the output.
-
Sort by month name:
Output:
Explanation: This command sorts the lines in months.txt based on the month names and displays the output.
-
Sort and remove duplicates:
Output:
Explanation: This command sorts the lines in file.txt, removes duplicate lines, and displays the unique sorted output.
Conclusion
-
The sort command is a versatile tool for sorting lines of text in files or standard input.
-
Various options can be combined to customize the sorting process.
-
It can handle numerical, alphabetical, and month-based sorting.