我编写了一个脚本,当值不在给定范围内时通知我。所有“超出范围”的值都记录在一组每日文件中。
每行都以专有的反向方式标记时间戳:yyyymmddHHMMSS
现在,我想改进脚本,并在自上次通知给定的超出范围值至少过去 60 分钟后收到通知。
我已经解决了以逆序方式打印日志的问题:
for i in $(ls -t /var/log/logfolder/*); do zcat $i|tac|grep \!\!\!|grep --color KEYFORVALUE; done
结果是:
...
20170817041001 - WARNING: KEYFORVALUE=252.36 is not between 225 and 245 (!!!)
20170817040001 - WARNING: KEYFORVALUE=254.35 is not between 225 and 245 (!!!)
20170817035001 - WARNING: KEYFORVALUE=254.55 is not between 225 and 245 (!!!)
20170817034001 - WARNING: KEYFORVALUE=254.58 is not between 225 and 245 (!!!)
20170817033001 - WARNING: KEYFORVALUE=255.32 is not between 225 and 245 (!!!)
20170817032001 - WARNING: KEYFORVALUE=254.99 is not between 225 and 245 (!!!)
20170817031001 - WARNING: KEYFORVALUE=255.95 is not between 225 and 245 (!!!)
20170817030001 - WARNING: KEYFORVALUE=255.43 is not between 225 and 245 (!!!)
20170817025001 - WARNING: KEYFORVALUE=255.26 is not between 225 and 245 (!!!)
20170817024001 - WARNING: KEYFORVALUE=255.42 is not between 225 and 245 (!!!)
20170817012001 - WARNING: KEYFORVALUE=252.04 is not between 225 and 245 (!!!)
...
不管怎样,我一直在计算两个时间戳之间的秒数,例如:
20170817040001
20160312000101
我应该怎么做才能计算两个时间戳之间经过的时间?
答案1
通过 GNU 实现date
或兼容,这将为您提供以秒为单位的日期(自 UNIX 纪元以来)
date --date '2017-08-17 04:00:01' +%s # "1502938801"
这将为您提供几秒内可读字符串形式的日期
date --date '@1502938801' # "17 Aug 2017 04:00:01"
因此,所需要做的就是将日期/时间戳转换为 GNUdate
可以理解的格式,使用数学来确定差异,然后输出结果
datetime1=20170817040001
datetime2=20160312000101
# ksh93 string manipulation (also available in bash, zsh and
# recent versions of mksh)
datestamp1="${datetime1:0:4}-${datetime1:4:2}-${datetime1:6:2} ${datetime1:8:2}:${datetime1:10:2}:${datetime1:12:2}"
datestamp2="${datetime2:0:4}-${datetime2:4:2}-${datetime2:6:2} ${datetime2:8:2}:${datetime2:10:2}:${datetime2:12:2}"
# otherwise use sed
# datestamp1=$(echo "$datetime1" | sed -nE 's/(....)(..)(..)(..)(..)(..)/\1-\2-\3 \4:\5:\6/p')
# datestamp2=$(echo "$datetime2" | sed -nE 's/(....)(..)(..)(..)(..)(..)/\1-\2-\3 \4:\5:\6/p')
seconds1=$(date --date "$datestamp1" +%s)
seconds2=$(date --date "$datestamp2" +%s)
# standard sh integer arithmetics
delta=$((seconds1 - seconds2))
echo "$delta seconds" # "45197940 seconds"
我们没有在这里提供时区信息,因此它假定为本地时区。您的日期时间秒数值可能与我的不同。 (如果您的值是 UTC,那么您可以使用date --utc
。)
答案2
答案3
使用expr
命令,例如:
expr 20170817040001 - 20160312000101
然后你就可以得到两个值之间的差异(以秒为单位):
expr 20170817040001 - 20160312000101
10505039900