I am new to UNIX. Please explain sort command. I have doubts related to sort field separator. E.g.: sort -k2, 2 filename, Please clarify. Please provide small example.
1 Answer
There is a syntax error in sort -k2, 2 filename There should not be a space delimiter in the -k2,2 option. In addition it would eliminate a possible source of confusion and/or error (depending on the contents of the file which is being sorted) to add either a dictionary order or a numeric sort option to the command in order to make it explicit how things should be sorted.
Examples
cat unsorted-file.txt # original unsorted file 9 8 7 6 55 44 3 2 1 sort -k1 -n unsorted-file.txt # example 1 3 2 1 6 55 44 9 8 7 sort -k3 -n unsorted-file.txt # example 2 3 2 1 9 8 7 6 55 44 sort -k1,3 -n unsorted-file.txt # example 3 3 2 1 6 55 44 9 8 7 sort -k2,3 -n unsorted-file.txt # example 4 3 2 1 9 8 7 6 55 44 Explanation
By default the field delimiter is non-blank to blank transition.
KEYDEF -k is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where F is a field number and C a character position in the field. Both are origin 1, and the stop position defaults to the line's end.
-k1 - first field
-k3 - third field
-k1,3 - start first field, stop third field
-k2,3 - start second field, stop third field
-n - compare according to string numerical value