3

I have a file which has content that looks like this:

19.58 1925 Alpha
20.40 1924 Otter
13.66 1920 Gold

I am trying to sort it "column by column" to output the following:

13.40 1920 Alpha
19.58 1924 Gold
20.66 1925 Otter

I have tried various combinations of code, e.g.:

cat files | sort -t. -k1,1n | sort -t " " -k2,2n -k3,3r k4,4n

but this doesn't output the wanted result. How could I achieve the sorting that I mentioned?

3
printf "%s.%s %s %s\n" $(paste <(awk -F'[. ]' '{print $1}' file | sort -n) <(awk -F'[. ]' '{print $2}' file | sort -n) <(awk -F'[. ]' '{print $3}' file | sort -n) <(awk -F'[. ]' '{print $4}' file | sort))

Output:

13.40 1920 Alpha
19.58 1924 Gold
20.66 1925 Otter
  • thanks . but how could i achieve "13.40" not "13.66" and so on result? – trolkura Nov 20 '15 at 0:00
  • I've updated my answer. – Cyrus Nov 20 '15 at 0:12
1

If you have GNU awk, then sorting can be done with a little help from special array PROCINFO:

awk -F '[. ]' '{for(i=1;i<NF+1;i++) a[i][NR]=$i} \
    END{PROCINFO["sorted_in"]="@val_num_asc"; \
        for(j=1;j<NF+1;j++){ I=0; for(i in a[j]) A[++I][j]=a[j][i]} \
            for(i=1;i<NR+1;i++){ printf A[i][1]"."; \
                for(j=2;j<NF+1;j++) printf A[i][j]" "; printf "\n"}}' file

The above may look complicated at first, but in fact is very simply - it just store the whole file in the array a, and at the end resort it to array A as desired. The main trick is to use @val_num_asc as we want to sort the columns by values in numeral ascending order.

It is should work for any number of rows and columns, just keep in mind that the whole file is stored in the memory so can be slow for large tables.

0
#!/bin/sh

for i in 1 2 3 4
do
    tr . " " < "${1:?}" | cut -d' ' -f$i | sort > $$-$i
done

paste -d. $$-[12] | paste -d' ' - $$-[34]

rm $$-[1234]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.