Sort
Sort command allows us to sort the contents in a file. We can sort the contents in many ways using sort command.
We are going to sort the file /course/sort/name.txt
Sort command allows us to sort the contents in a file. We can sort the contents in many ways using sort command.
We are going to sort the file /course/sort/name.txt
Now the sort command has sorted the names based on alphabetical order.
We can reverse the sorting order by using the switch -r
Sorting a file containing numbers
The following sort command sorted the numbers improperly. Its because sort normally consider everything as strings. To sort numbers we must use the switch -n. This switch will make the sort command to process the input as numeric.
The column separator is, by default, any blank character.
The column separator is, by default, any blank character.
Sorting numeric values
Sorting numeric values in reverse order.
Now we are going to sort a file which contains two fields separated by a ":"
In the following eg. we are sorting the file based on the first field. So we need to tell two things to sort command. One is the field separator and the second one is the field or the key that we want to to sort. Here the field separator is ":" and the key or the field that we want to sort is "1" or the first field. "-t" switch is used to provide the field separator and the "-k" switch is used to provide the key or the field.
Look at the output of the sort command. The first field of the file is a numeric value. That is why it is sorted in the wrong order. In order to sort them correctly we need to provide the "-n" switch too along with the sort command.
Sorting the second field. Here the key is "2" and they are strings so there is no need for "-n" switch.
Now we are sorting the second field in reverse order.
Sorting the ls -l output by size. We had avoided the line which begins with the word "total" by invert selecting using grep. By default the size is shown in the fifth field of ls command. That is why we have sorted the fifth field in the numerical order. By default sort uses the column separator as spaces.