sort command in linux is used to sort the content of text files in line by line. There are a lot of operations you can perform with the sort command.
sort command in linux/unix with examples | flags
![]() |
sort command in linux/unix with examples |
In this session, You will learn how to use the sort command in linux. It is used to sort the content of a file. Let's see how you can use it,
Open a file in sorted format
![]() |
simple sorting |
$sort fileName
- Type "sort filename" and press ENTER.
- Your file will be sorted in alphabetical order.
sorting months
- This will sort months in your file.
Numeric sorting
$sort -n fileName
- By using this "-n" flag. You can sort numbers in a file.
Random sort
- This will eliminate duplicate lines and sort all unique content in alphabetical order.
- But it is case sensitive i.e) capital letter is different from small letter.
- To make this case insensitive just add the "f" flag.
$sort -uf fileName
key map sorting
![]() |
key map sorting |
$sort fileName -k[column].[row]
- sort content by column and rows.
- In the column section, you need to give the column number which you want to sort.
- In the Row section, you need to type the corresponding column's row.
- The sorting process is done by selected columns and rows.
sort a CSV file
![]() |
sort CSV by number |
$sort -t "," fileName
- Use the above command to sort a CSV file by its number.
- This will sort your file by numbers.
- To sort by words.
![]() |
sort CSV by names |
$sort -t "," fileName -k[column].[row]
- This will sort your CSV file by alphabet.
Check the file is sorted
![]() |
check the file is sorted or not |
$sort -c fileName
- To check your file is sorted or not.
- If the file is not sorted it will display the line where the disorder begins.
- If the file is sorted there is no output.
Conclusion
- "-M" sort by months.
- "-n" sort by numbers.
- "-R" sort randomly.
- "-r" reverse sorting.
- "-u" sort unique content.
- "-f" case insensitive sorting.
- "-k" keymap sorting.
- "-t" input field seprator.
- "-c" check given file is sorted or not.
So these are the most frequently used operations in the sort command in linux.
HAVE A NICE DAY💕