Sam
Sam

Reputation: 2331

Sorting columns by column header left to right in bash

I want to sort a file by the column headers (left to right). I want to sort by alphanumerically from smallest number to largest (so that 2<10<21<100 ...) I want to ignore the first column in my sort (The first column will stay as the first column). I want no sorting of the columns from top to bottom.

Sample Input

FirstColumn Acolumn2 Acolumn10 Acolumn1 Bcolumn2 Bcolumn1
Word        pan      mat       toy      grass   bill
string      tan      pat       boy      mass    phil
characters  can      hat       coy      bass    ted

Sample Output

FirstColumn Acolumn1 Acolumn2 Acolumn10 Bcolumn1 Bcolumn2
Word        toy      pan      mat       bill     grass
string      boy      tan      pat       phil     mass
characters  coy      can      hat       ted      bass

Upvotes: 1

Views: 337

Answers (1)

Raman Sailopal
Raman Sailopal

Reputation: 12867

{
    if ( NR == 1 )
    {
            for (i=2;i<=NF+1;i++)
            {
                    cnt[i]=gensub("column","","g",$i)"*"i
            }
    asort(cnt)
    printf $1"\t"
    }
    for ( i=2;i<=NF;i++ )
    {
            split(cnt[i],cnt1,"*")
            printf $cnt1[2]"\t"
    }
    printf "\n"
}

The above awk code will work to a degree.

We first concentrate on the first row and ignore the first column (start the for loop from 2) We remove the "column" text from the string and then add the data to an array along with it's index position (separated with an asterix)

This array is then sorted and looped through to print out the data, utilising the index we added to the array.

The issue is sorting the data correctly. The standard sort will output data in the following order:

Acolumn1 Acolumn10 Acolumn2 Bcolumn1 Bcolumn2

Upvotes: 1

Related Questions