Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi I wonder if you can help me to calculate the time difference between to times.
Here is my file:
11:56:34 354940 5240832 453754
11:58:16 354788 5240832 453753I need to subtract the last time field from the 1st & output to another file called time_taken.txt
Thanks

Here is some code to work with. Just echo and redirect what you want to time_taken.txt.
I do not know the specifics of your input file. This code takes the LAST two lines found in the input file that start with a colon-delimited time field to use as the from/to times. If the ending time is earlier than the starting time, assumption is made that a single midnight has been traversed.
#!/bin/ksh
typeset -Z2 h1 m1 s1
typeset -Z2 h2 m2 s2
typeset -Z2 hh mm ssgrep '^..:..:.. ' file.in |
while read time remainder
doh1=$h2
m1=$m2
s1=$s2h2=$(expr "$time" : "\(..\):..:..")
m2=$(expr "$time" : "..:\(..\):..")
s2=$(expr "$time" : "..:..:\(..\)")done
echo "from=$h1:$m1:$s1 to=$h2:$m2:$s2"
seconds=$(echo "$h2*3600+$m2*60+$s2-($h1*3600+$m1*60+$s1)" | bc)
if [ "$seconds" -lt 0 ] ; then
((seconds=seconds+86400))
fihh=$(expr $seconds / 3600)
mm=$(expr \( $seconds - $hh \* 3600 \) / 60)
ss=$(expr $seconds - $hh \* 3600 - $mm \* 60)
echo "elapsed: $hh:$mm:$ss ($seconds seconds)"from=11:56:34 to=11:58:16
elapsed: 00:01:42 (102 seconds)

Hi Dave
I have 1 problem with the script
If I have more than 2 lines for the date
I get an error -
I need to calculate the 1st & last.
eg:
21:20:46 102349 Audit Number Commencing
21:44:11 DAYEND Completed Check Logfiles
21:51:22 DAYEND Completed Check Logfiles
21:52:10 DAYEND Completed Check Logfiles
21:52:52 DAYEND Completed Check Logfiles
21:53:36 DAYEND Completed Check LogfilesI need to calculate the difference between
21:53:36 to 21:20:46thanks for your help
Hamim

OK, this script will process the first and last lines:
#!/bin/ksh
typeset -Z2 h1 m1 s1
typeset -Z2 h2 m2 s2
typeset -Z2 hh mm ssgrep '^..:..:.. ' file.in |
while read time remainder
doh2=$(expr "$time" : "\(..\):..:..")
m2=$(expr "$time" : "..:\(..\):..")
s2=$(expr "$time" : "..:..:\(..\)")if [ ! "$h1" ] ; then
h1=$h2
m1=$m2
s1=$s2
fidone
echo "from=$h1:$m1:$s1 to=$h2:$m2:$s2"
seconds=$(echo "$h2*3600+$m2*60+$s2-($h1*3600+$m1*60+$s1)" | bc)
if [ "$seconds" -lt 0 ] ; then
((seconds=seconds+86400))
fihh=$(expr $seconds / 3600)
mm=$(expr \( $seconds - $hh \* 3600 \) / 60)
ss=$(expr $seconds - $hh \* 3600 - $mm \* 60)
echo "elapsed: $hh:$mm:$ss ($seconds seconds)"from=21:20:46 to=21:53:36
elapsed: 00:32:50 (1970 seconds)

Thanks Dave -
I have another problem where my script has to cd into each /home directory execute & cd into the next
I have a problem where it cannot exit out of the first & cd to the nextAny idead - Your help is very much appreciated
Thanks
Hamim

![]() |
![]() |
![]() |

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