[buug] Sorting columns? (SOLVED)

Claude Rubinson cmsclaud at uga.edu
Sun Aug 3 13:37:53 PDT 2003


awk to the rescue!  The following script does will sort columns by
column headings.  Requires gawk.


To use Aaron's example:

pear    fig     apple
bosch   mission galla
asian   beall   fuji

becomes:

apple	fig	pear	
galla	mission	bosch	
fuji	beall	asian	


#!/usr/bin/gawk -f

NR==1{
  # read original column order into array
  # note -- index is column name, value is column number
  for(i=1;i<=NF;i++){
    unsorted[$i]=i
  }

  # sort column names
  i=1
  for(colname in unsorted){
    sorted[i]=colname
    i++
  }
  asort(sorted)  # index is sorted order of column, value is column name
}


# output sorted columns
{
  for(i=1;i<=NF;i++){
    printf("%s\t",$unsorted[sorted[i]])
      if(i==NF) printf("\n")
	       }
}



More information about the buug mailing list