The Computer Oracle

How to UNIX sort by one column only?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping

--

Chapters
00:00 How To Unix Sort By One Column Only?
00:33 Accepted Answer Score 91
01:01 Answer 2 Score 11
01:25 Answer 3 Score 2
01:56 Thank you

--

Full question
https://superuser.com/questions/33362/ho...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#unix #sorting

#avk47



ACCEPTED ANSWER

Score 91


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.




ANSWER 2

Score 11


To only sort on the first column you should do:

sort -n -s -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




ANSWER 3

Score 2


None of the provided answers work generally for me.

Both sort -s -k 2 file1 and sort -n -k1,1 do additional sorting with this file:

# cat file1
 3 3 5
 3 2 3
 1 4 7
 0 1 2
 3 2 1

I just had to do this exact thing and ended up using a shell loop. This solution might not work well on a very large file because the entire file needs to be read for each unique value in the sorted column.

Here the file is sorted on column 2 only.

# awk '{print $2}' file1 | sort | uniq | while read index
do  
    awk -v var=$index '$2 == var { print $0}' file1 
done
 0 1 2
 3 2 3
 3 2 1
 3 3 5
 1 4 7