I'm on solaris and needed an answer without sort -s and the accepted answer wasn't working for me.
Joeyg on unix.com had the answer:
sort-one-column-only
cat tmp.txt
1 5
2 3
5 4
1 3
#Sort by 1st column leaving second stable sorted by the 1st.
cat -n tmp.txt | sort -k 2,2 | awk '{print $2,$3}'
1 5
1 3
2 3
5 4
#Sort by 2nd column leaving first stable sorted by the 2nd.
cat -n tmp.txt | sort -k 3,3 | awk '{print $2,$3}'
2 3
1 3
5 4
1 5
Different interpretation via comment is to sort a single column without affecting the rest:
#Sort by 1st column leaving other columns untouched:
cat -n tmp.txt | sort -k 2,2 | awk '{a[NR]=$2;b[$1]=$3} END {for (i=1;i<=NR;i++)print a[i]" "b[i]}'
1 5
1 3
2 4
5 3
Explanation:
cat -n adds rownums to force sort to do "sort -s" without GNU sort.
sort -k 2,2 sorts by the 1st column
NR is a built-in variable that holds the row num.
a[NR]=$2; puts the sorted column in a[1..4]
b[$1]=$3; puts the "unsorted" 2nd column in b[rownum from cat]
Then the for loop just outputs the two arrays.
What I needed which was the newest unique column 3 entries in the file. e.g.
cat tmp2.txt
5|1|3
4|2|1
1|3|2
3|4|1
2|5|2
cat -n tmp2.txt | sort -k 3 -rut '|' | awk '{print $2}'
5|1|3
2|5|2
3|4|1
-s
implies stable sort. You need to show your observation.sort
sorts lines of input based on the criteria that you provide.