jbsu32 jbsu32 - 2 months ago 7
Bash Question

Bash:: How to sort according to first numeric column of file?

4 lists are given like this. I need to sort them according to the

first numerical column
. Columns are seperated by
tabs
/
\t
.

France \t Paris \t 13.2 \t 14.2
Germany \t Munich \t Hamburg \t 16.9 \t 16.6
Norway \t 8.9 \t 9.1
Spain \t Barcelona \t Madrid \t Malaga \t 21.2 \t 19.4


After sorting, these columns will look like ->

Norway \t 8.9 \t 9.1
France \t Paris \t 13.2 \t 14.2
Germany \t Munich \t Hamburg \t 16.9 \t 16.6
Spain \t Barcelona \t Madrid \t Malaga \t 21.2 \t 19.4


They are sorted according to
8.9, 13.2, 16.9 & 21.2
.

I have tried with something like
sort -k 2n
or
sort -k 3n
, which sorts the lists according to the 2nd or the 3rd column. But,
8.9, 13.2, 16.9 & 21.2
are located in the 2nd, 3rd, 4th & 5th column in the lists. How can I solve this??

Answer

How about this:

sed -e 's/^[^0-9.]*\([0-9.]\+\).*$/\1\t\0/' input | sort -n | cut -f 2-

We extract the first numeric field and we insert it to the beginning of each line. Then we sort numerically all lines and then we remove the stuff that we added in the first step.

Comments