Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I know that the -k option for the Unix sort allow us to sort by a specific column and all of the following. For instance, given the input file:

2 3
2 2
1 2
2 1
1 1

Using sort -n -k 1, I get an output sorted by the 1st column and then by the 2nd:

1 1
1 2
2 1
2 2
2 3

However, I want to keep the 2nd column ordering, like this:

1 2
1 1
2 3
2 2
2 1

Is this possible with the sort command?

share|improve this question

migrated from stackoverflow.com Sep 1 '09 at 4:49

This question came from our site for professional and enthusiast programmers.

add comment

2 Answers 2

up vote 27 down vote accepted

Give this a try:

sort -s -n -k 1,1

The -s disables 'last-resort' sorting, which sorts on everything that wasn't part of a specified key.

The -k 1 doesn't actually mean "this field and all of the following" in the context of numeric sort, as you can see if you try to sort on the second column. You're merely seeing ties broken by going to the rest of the line. In general, however, you need to specify -k 1,1 to sort only on field one.

share|improve this answer
    
You are right. This is exactly what I needed. Thanks! –  ssn Aug 31 '09 at 16:31
    
is it possible to use join on the output of this sort? –  MiNdFrEaK Sep 27 '12 at 20:13
    
@MiNdFrEaK: The requirement of join is that the input be sorted on the fields you're joining on. So sure, this output is sorted on the first field, and you can join on it. –  Jefromi Sep 27 '12 at 21:49
    
I have 2 files, one having 2 columns, another having 1 column. The second file is sorted using sort -u. Now the task is I need to join this column with the first column of the first file, which is not sorted, so what will be the syntax? will this work? join -j 1 file2.txt sort -s -n -k 1 file1.txt? –  MiNdFrEaK Sep 28 '12 at 4:10
1  
The -k 1,1 (the ",1" part) doesn't work any better for me. What works is -s -k 1, with -n if you need it. –  Totor Aug 8 '13 at 15:12
show 2 more comments

To only sort on the first column you should do:

sort -n -k1,1

From Unix and Linux System Administration Handbook

sort accepts the key specification -k3 (rather than -k3,3), but it probably doesn’t do what you expect. Without the terminating field number, the sort key continues to the end of the line

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.