简体   繁体   中英

How can I process date strings in bash?

Does anyone have any idea how I could process input like this with bash? I would like to convert absolute time to relative time. My approach works but is VERY messy. Can anyone do better? Is there a cleaner way to do this?

Input:

| 2020-08-01 15:35:47.446 | message 1                    |
| 2020-08-01 15:35:48.446 | hi these                     |
| 2020-08-01 15:31:47.446 | do stuff now!                |

Output: Shows the time difference in milliseconds

0  message 1 
1000  hi these
60000  do stuff now!

Working (very dirty) approach :

while read line;
do echo $(echo "$(echo "$line" | cut -d' ' -f3 | cut -d':' -f2 | head -1) * 60000 + $(echo "$line" | cut -d' ' -f3 | cut -d':' -f3  | head -1) * 1000 - $baseval" | bc) $(echo "$line" | cut -d'|' -f3) ;
done < file.log

Looks like the question ask to move a series of abs timestamp to relative timestamp, using 'baseval' as the zero point in time.

It is possible to use date command (using the '+%S' to get seconds past epoch) to simplify calcualtion. If the file has many lines, this solution might not be ideal, as it calls the 'date' process for each line.

Worth noting some of the complexities is with parsing the input format - combination of fixed + delimited column. Code uses bash 'IFS' to split the line into components.

#! /bin/bash

function relative_time_ms {
    # Convert inputinto two tokens - relative seconds + nanoseconds
    local dd=($(date '+%s %N' -d "$1"))
    echo $((dd[0]*1000 + dd[1]/1000000 - baseval))
}

while IFS='|' read x ts msg ; do
    rel_time=$(relative_time_ms "$ts")
    echo "$rel_time | $msg"
done < file.log

Output:

0 |  message 1                    
1000 |  hi these                     
-240000 |  do stuff now! 

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