[英]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. 在Linux脚本中:我有一个文件,该文件中的每个消息都有两个时间条目。 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. 源时间是接收时间之后的3行,并不重要。
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: 2行后:一行中的一堆消息,每一行中,多次是:
sourceTimeStamp="2014-07-16T18:38:27Z"
you should be able to use date
like this (eg) 您应该可以使用这样的
date
(例如)
date +%s --date="2014-07-16T18:40:48Z"
to convert both timestamps into a unix timestamp. 将两个时间戳都转换为Unix时间戳。 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: 如果您有GNU的
date
(而不是busybox的date
),则可以通过以下方法在几秒钟内给出差异:
#!/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): 对于busybox的的
date
和ash
(现代可能/ 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
. 我会用
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. 以下脚本搜索感兴趣的行,将时间值转换为UNIX时间戳,并将其保存在
start
, end
变量中。 At the end of the script the difference will get calculated and printed: 在脚本末尾,将计算并打印差异:
timediff.awk : 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.