加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

如何使用AWK – 脚本减去毫秒

发布时间:2020-12-13 23:50:23 所属栏目:Linux 来源:网络整理
导读:我正在尝试创建一个awk脚本来减去连接的两个记录之间的毫秒数,例如: 通过命令行我可能会这样做: 输入: 06:20:00.12006:20:00.36106:20:15.20506:20:15.43106:20:35.07306:20:36.19006:20:59.60406:21:00.51406:21:25.14506:21:26.125 命令: awk '{ if (
我正在尝试创建一个awk脚本来减去连接的两个记录之间的毫秒数,例如:

通过命令行我可能会这样做:

输入:

06:20:00.120
06:20:00.361
06:20:15.205
06:20:15.431
06:20:35.073
06:20:36.190
06:20:59.604
06:21:00.514
06:21:25.145
06:21:26.125

命令:

awk '{ if ( ( NR % 2 ) == 0 ) { printf("%sn",$0) } else { printf("%s ",$0) } }' input

我会得到这个:

06:20:00.120 06:20:00.361
06:20:15.205 06:20:15.431
06:20:35.073 06:20:36.190
06:20:59.604 06:21:00.514
06:21:25.145 06:21:26.125

要正确减去毫秒:

awk '{ if ( ( NR % 2 ) == 0 ) { printf("%sn",$0) } }' input| awk -F':| ' '{print $3,$6}'

并避免负数:

awk '{if ($2<$1) sub(/00/,"60",$2); print $0}'
awk '{$3=($2-$1); print $3}'

目标是得到这个:

Call 1 0.241 ms
Call 2 0.226 ms
Call 3 1.117 ms
Call 4 0.91 ms
Call 5 0.98 ms

最后和平均.

我可能会按命令执行此命令.我不知道如何将它放入脚本中.

请帮忙.

解决方法

使用awk的一种方法:

script.awk的内容:

## For every input line.
{
        ## Convert formatted dates to time in miliseconds.
        t1 = to_ms( $0 )
        getline
        t2 = to_ms( $0 )

        ## Calculate difference between both dates in miliseconds.
        tr = (t1 >= t2) ? t1 - t2 : t2 - t1

        ## Print to output with time converted to a readable format.
        printf "Call %d %s msn",++cont,to_time( tr )
}

## Convert a date in format hh:mm:ss:mmm to miliseconds.
function to_ms(time,time_ms,time_arr)
{
        split( time,time_arr,/:|./ )
        time_ms = ( time_arr[1] * 3600 + time_arr[2] * 60 + time_arr[3] ) * 1000 + time_arr[4]
        return time_ms
}


## Convert a time in miliseconds to format hh:mm:ss:mmm. In case of 'hours' or 'minutes'
## with a value of 0,don't print them.
function to_time(i_ms,time)
{
        ms = int( i_ms % 1000 )
        s = int( i_ms / 1000 )
        h = int( s / 3600 )
        s = s % 3600
        m = int( s / 60 )
        s = s % 60
#       time = (h != 0 ? h ":" : "")  (m != 0 ? m ":" : "") s "." ms
        time = (h != 0 ? h ":" : "")  (m != 0 ? m ":" : "") s "." sprintf( "%03d",ms )
        return time
}

运行脚本:

awk -f script.awk infile

结果:

Call 1 0.241 ms
Call 2 0.226 ms
Call 3 1.117 ms
Call 4 0.910 ms
Call 5 0.980 ms

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读