Reputation: 40758
How can I sort an array of numbers in awk? Consider "sortNum.awk" :
{
split($0,a," ")
for (i in a) print a[i]
print "####"
asort(a)
for (i in a) print a[i]
}
Running with echo "4 3 2 1" | awk -f sortNum.awk
gives
1
4
3
2
####
4
1
2
3
I am using GNU Awk version 3.1.8.
Upvotes: 2
Views: 3047
Reputation: 781068
for (i in a)
doesn't select the indexes in numeric order, you need to do that explicitly.
{
n = split($0,a," ");
for (i = 1; i <= n; i++) print a[i];
print "####"
asort(a)
for (i = 1; i <= n; i++) print a[i];
}
Upvotes: 7