0

I have a log file like this:

2019.09.02 06:40:28 ---
2019.09.02 06:43:34 --- 
2019.09.02 06:43:41 ---

I need to read the file and get the difference between datetime "2019.09.02 06:43:34" -and- "2019.09.02 06:40:28" in hours minutes, and seconds.

while read date time message
do
    if [[ $date = $searched_date* ]] && [[ $message = *$searched_message* ]] ; then
      #how to convert $date and $time to unixtime?
    fi
done <"$LOG_FILE"

I am using AIX 7, and there is no such thing as date -d.

4
3

ksh93's printf understands your input format, so you could use:

end=$(printf '%(%s)T' "2019.09.02 06:43:34")
start=$(printf '%(%s)T' "2019.09.02 06:40:28")
printf '%d\n' "$((1567421014-1567420828))"

or more generally:

seconds=$(printf '%(%s)T' "$date $time")

To convert the difference in seconds to to hh:mm:ss:

printf '%d hours, %d minutes, and %d seconds\n' "$((diff / 3600))" "$(( (diff % 3600) / 60))"  "$((diff % 60))"
5
  • I don't have a great reference for the printf formats, but ast-users.research.att.narkive.com/sQqnDD7A/printf-t-question is a start. – Jeff Schaller Sep 3 '19 at 17:52
  • 2
    See also this test file in the source for examples of what is supported. – Stéphane Chazelas Sep 3 '19 at 18:03
  • result for printf '%(%s)T' "2019.09.02 06:43:34" is ()T just empty, maybe it has to do something with my ksh version? – serj Sep 3 '19 at 18:55
  • The result didn't have a newline, so does it exist at the beginning of your next prompt? The code does require ksh93, so make sure you're not invoking plain "ksh". – Jeff Schaller Sep 3 '19 at 18:58
  • yes this was the problem ksh93, other code also works as expected. Tnak you. – serj Sep 3 '19 at 19:48

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.