bash脚本转换毫秒到天:小时:分钟:秒:毫秒
问题描述:
我写了下面的bash脚本,以毫秒为单位转换为天:小时:分钟:秒:毫秒,使日志文件更具可读性:
I wrote the following bash script to convert milliseconds to Days:Hours:Minutes:Seconds:Milliseconds to make a log file more readable:
#!/bin/bash
### Constants ###
CON_DAYS=.0000000115741
CON_HOURS=.000000277778
CON_MINUTES=.000066667
CON_SECONDS=.001
### Variables ###
INPUT="$1"
cat $INPUT | awk -v CON_HOURS=$CON_HOURS -v CON_MINUTES=$CON_MINUTES -v CON_SECONDS=$CON_SECONDS -v CON_DAYS=$CON_DAYS '
{ $1=substr($0,0,10) }
{ MILLISECONDS = $1 }
{ DAYS = int(MILLISECONDS * CON_DAYS) }
{ MILLISECONDS = MILLISECONDS - int( DAYS / CON_DAYS ) }
{ HOURS = int(MILLISECONDS * CON_HOURS) }
{ MILLISECONDS = MILLISECONDS - int(HOURS / CON_HOURS) }
{ MINUTES = int(MILLISECONDS * CON_MINUTES) }
{ MILLISECONDS = MILLISECONDS - int(MINUTES / CON_MINUTES) }
{ SECONDS = int(MILLISECONDS * CON_SECONDS) }
{ MILLISECONDS = MILLISECONDS - int( SECONDS / CON_SECONDS ) }
{ $1 = DAYS":"HOURS":"MINUTES":"SECONDS":"MILLISECONDS"ms" }
{print}'
exit
输入文件的部分:
Section of Input File:
1882224617mS ATMChannel: [1] CMLinkLayer Rx: 'DialDigits' (ls)
1882224617mS ATMIO: [1] TONE DIAL (11 digits)
1882224617mS ATMChannel: [1] StateChange Connected->ToneDialing
有输出表明,它不能正常工作的几行:
There are several lines of output that shows that it is not working correctly:
22:19:224:14:186ms ATMChannel: [1] CMLinkLayer Rx: 'DialDigits' (ls)
22:19:224:14:186ms ATMIO: [1] TONE DIAL (11 digits)
22:19:224:14:186ms ATMChannel: [1] StateChange Connected->ToneDialing
几个小时后故障排除我无法找到我的错误。任何帮助将是非常美联社preciated。
After several hours of troubleshooting I am unable to find my error. Any help would be much appreciated.
答
拆分为毫秒级和第二,使用GNU日期,你应该比较容易得到的结果。
Split into millisecond and second, using GNU date, you should be easier to get the result
#!/bin/bash
INPUT="$1"
while read t rest
do
ms=$(echo $t|sed -r "s/.*(.....)$/\1/") # get Milliseconds 617mS
se=$(echo $t|sed -r "s/(.....)$//") # get seconds 1882224
days=$(echo $se / 3600 / 24 |bc)
d="$days:$(date -d "1970-01-01 $se seconds" +%H:%M:%S):$ms"
echo "$d $rest"
done < $INPUT