简体   繁体   中英

How can you can calculate the time span between two time entries in a file using a shell script?

In a Linux script: I have a file that has two time entries for each message within the file. A 'received time' and a 'source time'. there are hundreds of messages within the file.

I want to calculate the elapsed time between the two times.

2014-07-16T18:40:48Z  (received time)
2014-07-16T18:38:27Z  (source time)

The source time is 3 lines after the received time, not that it matters.

info on the input data:

The input has a lines are as follows:

TimeStamp:        2014-07-16T18:40:48Z  

2 lines later: a bunch of messages in one line and within each line, multiple times is:

sourceTimeStamp="2014-07-16T18:38:27Z"

you should be able to use date like this (eg)

date +%s --date="2014-07-16T18:40:48Z"

to convert both timestamps into a unix timestamp. Getting the time difference between them is then reduced to a simple subtraction.

Does this help?

If you have GNU's date (not busybox's), you can give difference in seconds with:

#!/bin/bash
A=$(date -d '2014-07-16T18:40:48Z' '+%s')
B=$(date -d '2014-07-16T18:38:27Z' '+%s')
echo "$(( A - B )) seconds"

For busybox's date and ash (modern probably / BusyBox v1.21.0):

#!/bin/ash
A=$(busybox date -d '2014-07-16 18:40:48' '+%s')
B=$(busybox date -d '2014-07-16 18:38:27' '+%s')
echo "$(( A - B )) seconds"

I would use awk . The following script searches for the lines of interest, converts the time value into a UNIX timestamp and saves them in the start , end variables. At the end of the script the difference will get calculated and printed:

timediff.awk :

/received time/ {
    "date -d "$1" +%s" | getline end 
}

/source time/ {
    "date -d "$1" +%s" | getline start
     exit
}

END {
    printf "%s seconds in between", end - start
}

Execute it like this:

awk -f timediff.awk log.file

Output:

141 seconds in between

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM