Sunday, August 2, 2009

Array sorting with Awk asort function


asort is a gawk-specific extension which sorts an array. More of asort can be found here and here

Lets see some array sorting example using awk asort function.
Input file:

$ cat file
KP
AS
DN

AO
BM
SE

ZW
ER
AI

Required output: Sort records in individual paragraph (each paragraph being separated by a newline), i.e. the output required is:

AS
DN
KP

AO
BM
SE

AI
ER
ZW


Awk solution using asort:

$ awk '
BEGIN{RS=""}
{
n=split($0,arr)
asort(arr)
for(i=0;i<=n;i++)
print arr[i]
}' file


Another example using asort: Horizontal sorting of fields in a file using awk asort.

Input file:

$ cat file
435 121 1 32
87 644 12 34
323 121 111 10


Required output: Sort the records in each row in descending order. i.e. output required is:

435 121 32 1
644 87 34 12
323 121 111 10

Awk solution:

$ awk '{
split($0,a)
asort(a)
for(i=NF;i>0;i--){
printf("%s ",a[i])
}
print ""
}' file

No comments:

© Jadu Saikia www.UNIXCL.com