Awk sort

April 23, 2009 at 03:37:16
Specs: AIX 5.3, 4 CPU / 32 GB RAM
I have a tape listing output which I would like sorted on column 3 (backup category).
I know this is achievable using sort however I was interested in an awk solution to get the "desired output".

$ cat tape.txt
T6601:DB2 pool:DB_BKUP
T6602:DB2 pool2:DB_BKUP
T6603:ACC pool:ACC_BKUP
T6604:FIN pool:FIN_BKUP
T6605:ACC pool:ACC_BKUP
T6606:DB pool:DB_BKUP
T6607:FIN pool6:FIN_BKUP
T6608:DB pool:DB_BKUP
T6609:ACC pool:ACC_BKUP


Desired output:
T6603:ACC pool:ACC_BKUP
T6605:ACC pool:ACC_BKUP
T6609:ACC pool:ACC_BKUP
T6601:DB2 pool:DB_BKUP
T6602:DB2 pool2:DB_BKUP
T6606:DB pool:DB_BKUP
T6608:DB pool:DB_BKUP
T6604:FIN pool:FIN_BKUP
T6607:FIN pool6:FIN_BKUP


See More: Awk sort

Report •


#1
April 23, 2009 at 04:01:58
i see you are working on AIX. if you have gnu awk, you can use its internal function asort or asorti. However, the unix command sort is still the "best" choice for your case.

Unix Win32 tools | Gawk for Windows


Report •

#2
April 23, 2009 at 19:57:45
First, ghostdog is giving you good advice; the external sort command is the way to go. However, In the book, "The Awk Programming Language", the authors presented a quick sort function that sorts an awk array.

Rearrange each line placing the sort key (3rd field) first, do the quick sort, print the array placing the fields back in the proper order. It's not pretty:

#!/bin/ksh

 # use awk for non-Solaris
nawk ' BEGIN { FS=":" }
{
  myline=$3":"$1":"$2
  A[NR]=myline
} END {  qsort(A, 1, NR)
         for (i=1; i <= NR; i++)
            {
            split(A[i], B)
            myline=B[2]":"B[3]":"B[1]
            print myline
            }
      }

# awk quick sort
function qsort (A, left, right,   i, last) {
   if (left >= right)   # do nothing if array has less than 2 elements
      return
   swap(A, left, left + int((right-left+1)*rand()))
   last = left  # A[left] is now partition element
   for (i = left+1; i <= right; i++)
     if (A[i] < A[left])
        swap(A, ++last, i)
   swap(A, left, last)
   qsort(A, left, last-1)
   qsort(A, last+1, right)
}

function swap (A, i, j,  t) {
   t = A[i]; A[i] = A[j]; A[j] = t
}
' < data.txt


Report •

#3
April 24, 2009 at 02:07:22
Many thanks for the above replies. I'd have to agree the Unix sort command does by far appear to be the simpliest approach to the problem. Thanks again ghostdog and nails for your advice.

Report •

Related Solutions


Ask Question