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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Unix (awk)

Status
Not open for further replies.

malpa

Technical User
Feb 8, 2004
122
CO
Hi

I would like to do this


awk ' BEGIN{FS=";"}
{ n[$1";"$2]++; l[$1","$2]+=$7 }
END{
for ( i in n) {
print i":"n";"l
} ' /input/file


but only with arrays in bash or sh or csh o ksh script. is it possible.??


Thanks malpa

 
Not sure about csh, but as far as I know arrays in bash, sh and ksh can only be indexed by integers, so you have to approach it differently... try this perhaps:

Code:
tot=0
n=0
sort -t';' -k 1,1 -k 2,2 /input/file | while IFS=';' read a b c d e f g
do
        if [[ "$prev" != "" && "$a;$b" != "$prev" ]]
        then
                echo "$prev:$n;$tot"
                tot=0
                n=0
        fi
        ((n=n+1))
        ((tot=tot+$g))
        prev="$a;$b"
done
echo "$prev:$n;$tot"

Incidentally, I think there's an error on the second line of your awk script; shouldn't the index of l have a semi-colon too, rather than a colon?

Code:
      { n[$1";"$2]++; l[$1"[COLOR=red];[/color]"$2]+=$7 }

Annihilannic.
 
Hi

If you want associative arrays in [tt]bash[/tt], take a look at the libbash project. Its install package contains a library, hashstash. That may help you.

( Note, that I never used it so I know nothing more about it. I just suppose it can be quite slow as it is based on [tt]eval[/tt]. )

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top