Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I have a file with content
1 arnone 100
1 arnone 100
4 temp 20
2 temp 10
... and so on
2 arnone 200
6 temp 30how do i achieve this result?
thanks in advance

Try:
#!/usr/bin/ksh
for var in $(cat tfile|awk '{print $2}'|sort -u);do
grep $var tfile > temp.file
ftot=0
stot=0
while read line;do
fnum=$(print $line|awk '{print $1}')
snum=$(print $line|awk '{print $3}')
ftot=$(($ftot+$fnum))
stot=$(($stot+$snum))
done < temp.file
print $ftot $var $stot
done

This is a standard control-break approach. When the key field changes, a summary line is printed and the accumulators reset to zero.
It assumes that the input file is already sorted by the key field. If not, you could insert a sort command in this script.
Instead of shell script, awk could do the same control-break processing on a sorted file. Or awk could process an unsorted file, accumulating the values in an array, and that would actually be less code.
#!/bin/bash
holdkey=
ftot=0
stot=0while read num1 key num2
do
if [ "$key" != "$holdkey" ] ; then
if [ "$holdkey" != "" ] ; then
echo $tot1 $holdkey $tot2
fi
holdkey=$key
tot1=0
tot2=0
fi
((tot1=tot1+num1))
((tot2=tot2+num2))
done < filein# print totals for final key group
echo $tot1 $holdkey $tot22 arnone 200
6 temp 30

![]() |
Help with shell script
|
sed bug?
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |