Question

I'm trying to sort an array (dictionary) by their values ​​while maintaining the correct keys. I have a problem. I have written a code that performs the task, but when I call the function repeatedly printTop only works well the first call.

My gawk function is:

function printTop(n,array){
    for (i in array) tmpidx[sprintf("%12s", array[i]),i] = i
    num = asorti(tmpidx,ind)
    j=0   
    for (i=1; i<=num; i++) {
        split(ind[i], tmp, SUBSEP)
        indices[++j] = tmp[2]  # tmp[2] is the name
    }   
    for (i=num; i>num-n && i>0; i--)print indices[i]"\t"array[indices[i]]
}

I call it in the next script:

'gawk{
    IPsrcPkg[$1]+=$8;
    IPdstPkg[$2]+=$8;
    IPsrcBytes[$1]+=$9;
    IPdstBytes[$2]+=$9;
}
END {
    printTop(sizeTop,IPdstBytes,NULL);
    printTop(sizeTop,IPsrcPkg,NULL);
    printTop(sizeTop,IPdstPkg,NULL);
    printTop(sizeTop,IPsrcBytes,NULL);
}'

The result is:

TOP5 IP_DST por Bytes:
148.244.42.179  15404514
187.137.83.175  11962637
148.244.42.173  10698849
173.194.46.21   9479857
70.37.119.14    5551644

TOP5 IP_SRC por paquetes:
148.244.42.179  32479
187.137.83.175  11626
148.244.42.173  34471
173.194.46.21   32503
70.37.119.14

TOP5 IP_DST por paquetes:
148.244.42.179  22127
187.137.83.175  14899
148.244.42.173  33697
173.194.46.21   32763
70.37.119.14    5548

TOP5 IP_SRC por Bytes:
148.244.43.5    24157292
148.244.42.179  11055963
65.52.32.92     15308768
187.137.83.175  700023
148.244.42.179  11055963

You can see how the second, third, and fourth Tops do not have any order. If I change the call order, the program works well always for the first call function. Any idea? Any solution?
Thank you for your time!
Victor

Était-ce utile?

La solution

You have forgot to declare the local variables in printTop. Try:

function printTop(n,array, i, tmpidx, j, num, indices) {
    for (i in array) 
        tmpidx[sprintf("%12s", array[i]),i] = i
    num = asorti(tmpidx,ind)
    j=0   
    for (i=1; i<=num; i++) {
        split(ind[i], tmp, SUBSEP)
        indices[++j] = tmp[2]  # tmp[2] is the name
    }   
    for (i=num; i>num-n && i>0; i--)
       print indices[i]"\t"array[indices[i]]
}

(Assuming you remove the NULL in printTop(sizeTop,IPdstBytes,NULL); . That is: call the function as printTop(sizeTop,IPdstBytes); instead)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top