gpt4 book ai didi

language-agnostic - 如何按秒对 grep 结果进行分组

转载 作者:太空宇宙 更新时间:2023-11-04 10:30:52 25 4
gpt4 key购买 nike

我在日志文件中有以下内容,

01:31:01,222 收到事件
01:31:01,435 收到事件
01:31:01,441 收到事件
01:31:01,587 收到事件
01:31:02,110 收到事件
01:31:02,650 收到事件
01:31:02,869 收到事件
01:31:03,034 收到事件
01:31:03,222 收到事件

我想按秒对它进行分组并计算每组中的行数以输出以下内容,

01:31:01 4
01:31:02 3
01:31:03 2

理想情况下,我喜欢在一个简单的 awk 脚本中执行此操作,而不必求助于 perl 或 python,有什么想法吗?谢谢。

最佳答案

听起来像是 awk 的工作:

awk -F, '{a[$1]++}END{for(i in a){print i, a[i]}}' file.txt

输出:

01:31:01 4
01:31:02 3
01:31:03 2

解释:

我正在使用选项 -F(字段分隔符)并将其设置为 ,。这使得在字段 1 ($1) 中获取精确到秒的时间变得容易。

脚本本身的解释(多行形式):

# Runs on every line and increments a count tied to the first field (the time)
# (The associative array a will get created on first access)
{a[$1]++}

# Runs after all lines have been processed. Iterates trough the array 'a' and prints
# each key (time) and its associated value (count)
END {
for(i in a){
print i, a[i]
}
}

关于language-agnostic - 如何按秒对 grep 结果进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26764984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com