2

I have a text file containing flight times, hours and minutes separated by colon sign, one per line:

00:50
00:41
00:43
00:50
01:24

I am currently using Apple's Numbers application with a simple formula to calculate the total time (result being 4:28 for the example data above).

However, I was wondering if there is an easier way to achieve this. A perl script would work all right, but how about using Unix shell commands and/or scripting? I am basically looking for anything short and simple.

Yes, I can manage with Numbers, but this would be nice to know and learn :).

p.s. Posting perl script to achieve this in case someone else needs it:

#! /usr/bin/perl
while (<>) {
  chomp;
  ($hours, $minutes) = split (/:/, $_);
  $totalhours += $hours;
  $totalminutes += $minutes; 
}
while ($totalminutes > 59) {
  $totalhours++;
  $totalminutes -= 60;
}
printf ("%d:%02d\n", $totalhours, $totalminutes);
4

As you note, there are many possibilities. The following versions with awk are roughly equivalent to the perl you included with your question:

  1. (with GNU awk):

    awk -F : '{acch+=$1;accm+=$2;} ENDFILE { \
    print acch+int(accm/60)  ":" accm%60; }' [inputfile]
    
  2. (with "POSIX" awk):

    awk -F : '{acch+=$1;accm+=$2;print acch+int(accm/60) \
                 ":" accm%60; }' [inputfile] | tail -1
    
  • Useful for calculating cumulative times (without the tail pipe). +1 – Simo A. Sep 28 '14 at 21:38
2

A "one-liner" version in Perl:

perl -F: -lane '$a+=$F[0]*60+$F[1];END{printf "%02d:%02d\n",$a/60,$a%60}' file
  • Added ct () { perl -F: -lane '$a+=$F[0]*60+$F[1];END{printf "%02d:%02d\n",$a/60,$a%60}' "$@"; } to my .bash_profile. Nice! – Simo A. Sep 28 '14 at 21:45
  • perfect! if i get hours:minutes:seconds this will be the code perl -F: -lane '$a+=$F[0]*3600+$F[1]*60+$F[2];END{printf "%02d:%02d:%02d\n",$a/3600,$a/60,$a%60}' file – Ambigus9 Mar 8 at 1:11
1

This should work in any POSIX-compatible shell:

#!/bin/sh
# usage: time-add.sh < times.txt
sum=0
while IFS=: read -r hours minutes; do
    sum=$(($sum + $hours * 60 + $minutes))
done
total=$(($sum / 60)):$(($sum % 60))
echo $total

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.