Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How to (numerically) sort a specific column in a text file, without affecting other columns (irrespective of whether they are sorted or unsorted)? On other threads I found -s argument, but it does sort other columns.


$ cat tmp.txt
1 1
2 3
5 4
1 3

$ sort -s -n -k1,1 tmp.txt
1 1
1 3
2 3
5 4
share|improve this question
No, -s implies stable sort. You need to show your observation. –  devnull Feb 16 '14 at 8:59
What's wrong with the output? What did you expect? –  devnull Feb 16 '14 at 9:02
@devnull second column should remain as it is. –  user13107 Feb 16 '14 at 9:03
Interchange the first and last lines of your sample file and run the same command. You'll figure. –  devnull Feb 16 '14 at 9:03
Why will the second column remain as is? sort sorts lines of input based on the criteria that you provide. –  devnull Feb 16 '14 at 9:04

2 Answers 2

up vote 3 down vote accepted

As mentioned in the comments, you can't achieve what you want using sort alone.

You could cut the input file, feed relevant part to sort, and paste those.

$ paste -d' ' <(cut -d' ' -f1 input | sort -n) <(cut -d' ' -f2- input)
1 1
1 3
2 4
5 3
share|improve this answer

A solution in perl:

perl -lane '
 push @first , $F[0];
 push @second, $F[1];
    @first = sort { $a <=> $b } @first;
    print "$fist[$_] $second[$_]" for (0..$#first)
 }' your_file

It assumes the first column (the one to be sorted) consists only of numerical data.

share|improve this answer

Your Answer


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.