Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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);
share|improve this question

2 Answers 2

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
    
share|improve this answer
    
Useful for calculating cumulative times (without the tail pipe). +1 –  Simo A. 7 hours ago

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
share|improve this answer
    
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. 7 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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