jbsu32 - 2 months ago 7

Bash Question

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

`first numerical column`

`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`

`sort -k 3n`

`8.9, 13.2, 16.9 & 21.2`

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.

Source (Stackoverflow)

Comments