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

sum of numbers having different prefixes

Status
Not open for further replies.

lnbnatera

Technical User
Feb 14, 2006
54
HK
hi,

i have two columns as follows:

129 MB
23 KB
100 B
90 GB
1 KB
4 KB
34 MB
29 MB
10 GB

the usual thing that i do is "grep" out using the units to sort things out according to prefixes then add them (with respect to their prefixes. then add the 4 sums that i get.

something like
$ grep 'MB' file.txt > file-MB.txt
$ grep 'KB' file.txt > file-KB.txt
... and so on ...

then,
$ awk -f sum.awk file-MB.txt
<outputs a number>
$ awk -f sum.awk file-KB.txt
<outputs a number>
... and so on ...

then i add all those that i get to have a sum.

is a simpler way to do this in awk in just one shot? something like
$ awk -f new_sum_awk.awk file.txt
<sum>

thanks
 
A starting point for new_sum_awk.awk:
BEGIN{a["B"]=1;a["KB"]=1024;a["MB"]=1024*1024;a["GB"]=1024*1024*1024}
{t+=($1*a[$2])}
END{print "total",t}

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top