Linux Sort Command: Complete Guide
The sort command is a very commonly used command in the Linux system that is used to perform sorting operations on text files. There are many different options available for the sort command, here is an explanation of some commonly used options for the sort command.
- -b: Sort ignoring leading whitespace characters on each line.
- Sort the text in alphabetical order, ignoring non-alphanumeric characters.
- Ignoring character case, sort the data.
- -g: Sort in numerical order (e.g. 10 will come after 2, not before).
- -n: Sorting in numerical order.
- – r: Sort in reverse order (descending).
- – Separator: specifies the field separator used during sorting, defaulting to a tab.
- -k
[ ]: Specify the range of fields to be sorted. - -u: Remove duplicate lines.
- -o
The basic syntax for sorting using the sort command is as follows:
sort [options] [file name]
For example, to sort a text file in dictionary order and output the result to another file, you can use the following command:
sort -d input.txt -o output.txt
This will output the contents of input.txt sorted in dictionary order to output.txt.
It is important to note that the sort command by default treats all text lines as sorting keys, so if you need to sort by specific fields, you can use the -k option to specify the range of fields. For example, to sort a tab-delimited text file in dictionary order by the second field, you can use the following command:
sort -t$‘\t’ -k2 input.txt -o output.txt
The content in input.txt will be sorted in dictionary order based on the second field and then output to output.txt.