Calculate the time difference in batches with pipelines under Linux and Mac

Preface

During the internship in the company, you need to calculate the startup time of a certain service, that is, the length of time the task is submitted to the real Start of the server. Due to the large number of changed services, consider writing a shell script to achieve it.

Example

The step of extracting time from the log is omitted, and the extracted result is saved as time.log as follows.

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

You can directly write a shell script for loop for processing, but I use the pipeline usage I just learned to
cat time.log |while read -r row; do echo $row; doneprint each row of rows. I
Insert picture description here
only need to convert the time string to a timestamp when printing, and then I can successfully convert the string to time
under date -d $row +%s
mac under Linux. date -j -f "%Y-%m-%d %H:%M:%S" $row +%s
Insert picture description here
poke, we need to use expr $row - 1614390737to calculate

Among them, 1614390737 is the timestamp of the task I submitted. It has been calculated first. You can also nest a date function, but that nesting is a bit complicated

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

Get the following time difference, if you need minutes and hours, you can convert it in expr
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44112790/article/details/114238683