以awk的特定顺序打印文件 [英] Print file in particular order in awk

查看:173
本文介绍了以awk的特定顺序打印文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注此链接 https://stackoverflow.com/a/54599800/10220825

file.txt

Iteration 1
RAM: +2s
Cache: +142ms (total +417ms)

Iteration 2
RAM: +184ms
Cache: +172ms
Searchms: +131ms (total +385ms)

Iteration 3
RAM: +149ms
Searchms: +3.2s

我想从时间值中删除ms or s,而不是从名称中删除(例如,它不应删除Searchms to Search).另外,如果时间值包含s,我想将s into ms转换为multiply into 1000,并相应地打印结果.

I want to remove the ms or s from the time value but not from name (example it should not remove Searchms to Search). Also I want to convert s into ms by multiply into 1000 if the time value contains s and print result accordingly.

预期输出:

RAM: 2000 184 149
Cache: 142 172
Searchms: 131 3200

try.awk

/:/{vals[$1]=vals[$1] OFS $2+0}
END {
         for (key in vals)
          print key vals[key]
}

执行时:awk -f try.awk file.txt

代码输出:

Cache: 142 172
Searchms: 131 3.2
RAM: 2 184 149

在我的输出s is not converting to ms.中,请建议我如何修改上述源代码try.awk将s转换为ms.

In my output s is not converting to ms. Please suggest me how I modify above source code try.awk to convert s to ms.

新测试用例: file.txt

Iteration 1
RAM: +2s342ms

Iteration 2
RAM: +2s

Iteration 3
RAM: +149ms

代码:

/:/ && $2 ~/ms$/{vals[$1]=vals[$1] OFS $2+0;next}
/:/ && $2 ~/[^m]s$/{vals[$1]=vals[$1] OFS ($2+0)*1000}
END {
         for (key in vals)
          print key vals[key]
}

预期输出:

RAM: 2342 2000 149

输出:

RAM: 2 2000 149

推荐答案

您可以使用以下awk脚本:

/:/ && $2 ~/ms$/{vals[$1]=vals[$1] OFS $2+0;next}
/:/ && $2 ~/[^m]s$/{vals[$1]=vals[$1] OFS ($2+0)*1000}
END {
         for (key in vals)
          print key vals[key]
}

这将产生输出:

awk -f try.awk file.txt 
Cache: 142 172
Searchms: 131 3200
RAM: 2000 184 149

说明:

  • 条件$2 ~/ms$/将检查我们是否有ms行,在这种情况下,执行与以前相同的逻辑,并且next将强制awk跳至下一行.
  • /:/ && $2 ~/[^m]s$/{vals[$1]=vals[$1] OFS ($2+0)*1000}当我们达到此范围时,我们知道我们在s中有一行带有单位的行,并将其乘以1000将其转换为ms.
  • The condition $2 ~/ms$/ will check if we have a line with ms in this case the same logic is done as before and the next will force awk to jump to the next line.
  • /:/ && $2 ~/[^m]s$/{vals[$1]=vals[$1] OFS ($2+0)*1000} when we reach this scope we know that we have a line with units in s and we multiply it by 1000 to convert it to ms.

为了满足您的新要求,我已将try.awk修改为:

To answer to your new requirements, I have adapted the try.awk into:

/:/ && $2 ~/[0-9]+s[0-9]+ms$/{split($2,buff,/s/);vals[$1]=vals[$1] OFS (buff[1]+0)*1000+buff[2];next}
/:/ && $2 ~/ms$/{vals[$1]=vals[$1] OFS $2+0;next}
/:/ && $2 ~/[^m]s$/{vals[$1]=vals[$1] OFS ($2+0)*1000}
END {
         for (key in vals)
          print key vals[key]
}

输入:

$ cat file2.txt 
Iteration 1
RAM: +2s342ms

Iteration 2
RAM: +2s

Iteration 3
RAM: +149ms

输出:

$ awk -f try.awk file2.txt 
RAM: 2342 2000 149

这篇关于以awk的特定顺序打印文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆