Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sort in awk

Status
Not open for further replies.

praywin

Programmer
Feb 6, 2003
31
IN
Hi,
Is there any way I can use sort inside awk.
i.e.
awk '
{
if (NF==2) {ar[$2]+=$1};
print
}
END{
print("total");
for(a in ar) {print(ar[a],a) }
}'

I want the for loop output to be sorted.

test input
----------------------------
Sams Dept Store
3 apple
4 banana
John
5 orange
3 apple
6 banana
----------------------------

Expected Output
Sams Dept Store
3 apple
4 banana
John
5 orange
3 apple
6 banana
total
5 orange
6 apple
10 banana

Is there anyway I can do the sorting inside awk

Cheers,
Pravin.





 
What's your sorting citeria? Your expected sample is somewhat confusing. vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Hi Vlad,
The expected output is that it should print the input as it is and then print the totals. The totals should be sorted numerically on the first field.
To achieve this. I add up the counter in the body and keep printing the lines as it is. In the END part I do all the post processing of printing the totals and hopefully sort.
I already have a bash script solution using files and sort. I want to know how I can do it all in awk.
Cheers,
Pravin.
 
A sort on your array values will result in
misplacing your array indices. Your data ordering
will be kaput.

Example:
Code:
function bsort(arr, i,x) {
for (i in arr) {
     for (x in arr) {
          if (arr[i] < arr[x]) {
              swap(arr,i,x)
          }
      }
  }
}


 function swap(array,ind1,ind2) {
            sw = array[ind1]
            array[ind1] = array[ind2]
            array[ind2] = sw
 }


{
    if ($1 ~ /[^a-zA-Z]+/) {
       ar[$2] = $1
   }
}
END {
      printf &quot;Pre-sort\n&quot;
      for (all in ar) {
            print ar[all],all
       }  

       bsort(ar)

       printf &quot;\nPost-sort\n&quot;
       for (all in ar) {
            print ar[all],all
       }  
}
OP:
Pre-sort
5 orange
3 apple
6 banana

Post-sort
3 orange
5 apple
6 banana



 
Try something like this:
Code:
awk '{
  if(NF==2) ar[$2]+=$1
  print
}
END{
  print &quot;total&quot;
  for(a in ar) print ar[a],a | &quot;sort -n&quot;
}' /path/to/input

Hope This Help
PH.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top