How to get total time using awk

Hi guys,

I can't find a solution to sum the h:m:s: columns.

28/05/2010  03h 29min 34seg ADSL TELEMAR
28/05/2010  12h 19min 21seg ADSL TELEMAR
29/05/2010  04h 20min 02seg ADSL TELEMAR
29/05/2010  04h 31min 45seg ADSL TELEMAR
30/05/2010  06h 10min 43seg ADSL TELEMAR

Thanks

Like this?

awk '{h+=substr($2,1,2); m+=substr($3,1,2); s+=substr($4,1,2)} END{print h,m,s}' infile
29 109 145

Use below code

awk ' BEGIN {toth=0;totm=0;tots=0;}{
toth=toth+substr($2,1,2);
totm=totm+substr($3,1,2);
tots=tots+substr($4,1,2);}
END{print "Total Hours : " toth ;
print "Total Min : " totm
print "Total Second : " tots}' file1

no need substr, awk can recognize the number.

awk '{h+=$2; m+=$3; s+=$4} END{print h,m,s}' infile 

This will give 0 0 0 only.substr is required.

I confirm rdcwayx' post, awk doesn't need the substr.

awk '
{
  h += $2;
  m += $3;
  s += $4;
}
END {
  m += int(s / 60);
  s  = s % 60;
  h += int(m / 60);
  m  = m % 60;
  printf "%03dh %02dmin %02dsec\n", h, m, s;
}
' inputfile

Inputfile:

28/05/2010  03h 29min 34seg ADSL TELEMAR
28/05/2010  12h 19min 21seg ADSL TELEMAR
29/05/2010  04h 20min 02seg ADSL TELEMAR
29/05/2010  04h 31min 45seg ADSL TELEMAR
30/05/2010  06h 10min 43seg ADSL TELEMAR

Output:

030h 51min 25sec

Jean-Pierre.

1 Like

They are both correct - even awk on AIX (which isn't that versatile like GNU sed for example) can see the difference from numbers to letters without a delimeter between them. So leave out substr :slight_smile:

Thanks Jean Pierre. That's exactly what I needed.

awk '{sum+=$2*3600+$3*60+$4} 
       END {h=int(sum/3600);m=int((sum-h*3600)/60);s=sum-h*3600-m*60
         printf "Total %s hours %s minutes %s seconds", h,m,s}' urfile

Total 30 hours 51 minutes 25 seconds