This article explains how to use the sort command to perform sort operations on specific columns in a file.
The sort command is easy to use and very useful in daily Linux operations. The general syntax of the command is as follows: The
options passed to the command modify the way the file is sorted and the specific conditions for sorting the destination file. You can skip the options to use the default sort parameters.
By default, the sort: command
- sorts the alphabets in ascending order
- Letters come after numeric values
- Assigns higher priority to lowercase letters than uppercase letters.
to sort a file without options
Once we execute the sort command against the file, we get the information sorted in alphabetical (ascending) order
NOTE: Numeric values take precedence from the previous example.
Sort You can use the following options together with the raw command to modify how values are sorted.
- -n – sorts in numeric values
- h – compares human-readable numbers such as 1k, 1G
- random order but group identical keys. -r – sort the values in reverse (descending order
- o – save ouput to a
- Do not order if it is true
- -u: Displays unique values only.
- -k – sort the data through a specific key (useful for sorting data into columns).
-R – sort in
-c file – check if the input file is sorted;
Those are some popular options that you can tweak to get the best neat result. For more options, refer to the manual.
How to sort in Linux Bash by numeric values
How to sort in
Linux Bash by
order To sort the input in reverse order
, we use the -r flag. For example:
The above command will sort in ascending alphabetical order (numeric values first) and reverse order
How to sort in Linux Bash
Sort allows us to sort a file by columns using the -k option. Let’s start by creating a file with more than one column. In order, we separate a column by a single space.
In the example file below, we have six columns.
To sort the
previous captains file by their century, we can specify the -k followed by the column number as:
Once we specify the column to sort the data, the sort command will try to sort the values in ascending order. In the example above, the command sorts the values from the earliest century to the most recent.
To sort by name, set the sort column to 1:
to save sorting output to a file To save the
sorted output to a file, we can use the -o option as:
The above command will sort the captains file .txt by the 5th column and save the result in the captains_century.txt file.
That’s the end of this tutorial on sort command on Linux. We cover the basics of using the sort command to get the most out of sorted data. Feel free to explore how you can use the command order.