Linux和Mac下用管道批量计算时间差

前言

在公司实习的时候,需要计算某个服务的启动时间即提交任务到Server真正Start的时长。由于改服务个数较多,考虑编写shell脚本来实现。

示例

从日志中提取时间的步骤省略掉,提取出来的结果如下保存为time.log。

2021-02-27 09:59:28
2021-02-27 09:59:48
2021-02-27 10:03:33
2021-02-27 09:58:40
2021-02-27 09:59:14
2021-02-27 09:55:30
2021-02-27 10:01:23
2021-02-27 09:58:46
2021-02-27 10:01:20

可以直接写shell脚本for循环进行处理,但是我采用自己刚学习的管道用法
cat time.log |while read -r row; do echo $row; done打印每一行row
在这里插入图片描述
只需要在打印的时候将时间字符串转为时间戳即可
linux下date -d $row +%s
mac下date -j -f "%Y-%m-%d %H:%M:%S" $row +%s
在这里插入图片描述
成功将字符串转为时间戳,接下来需要用expr $row - 1614390737来计算

其中1614390737是我提交任务的时间戳已经先计算好,也可以再嵌套一个date函数但那样嵌套有点复杂

cat time.log | while read -r row; do echo `date -j -f "%Y-%m-%d %H:%M:%S" $row +%s`; done | while read -r row; do echo `expr $row - 1614390737`; done

得到如下的时间差,如果需要分钟、小时可以在expr的时候进行换算
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44112790/article/details/114238683