Please explain how to use sort command in unix

2

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.

user607585

Posted 2016-06-18T04:37:52.477

Reputation: 29

2Please read man sort Come back when you have an explicit question about what you don't understand. – DavidPostill – 2016-06-18T13:12:55.957

@David Postill 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 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. – karel – 2016-06-18T16:08:04.597

Could you please [edit] your question to tell us exactly where you're confused? – Ben N – 2016-06-18T16:58:10.977

As I wrote in my answer the command in the question will always return at least one error message and sometimes it will return another error message after that, depending on the contents of the file being sorted. – karel – 2016-06-18T17:03:03.737

Answers

2

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

karel

Posted 2016-06-18T04:37:52.477

Reputation: 11 374

1-n is mandatory to compare number, else, as a string, 10 is lower that 2. – Archemar – 2016-06-19T07:36:59.657