首页 > 解决方案 > 使用 shell/bash 计算每对引用地图的频率

问题描述

我的数据如下所示:

 abc.com  Hello World Ann
 abc.com  Hi there friend
 def.com  Hello Sam
 def.com  Hello Dan
 abc.com  Hello World Mary

字符串 B 可以包含不同的文本,但我已经从该字符串中提取了关键字以映射到下面的数组,(这不是字符串 B 的完全匹配)

keywords=( ["Hello World"]="h1" ["Hello"]="h2" ["Hi there"]="h3" )

我想生成这样的输出:

A         Key    Count
abc.com   h1    2
abc.com   h3    1
def.com   h2    1

其中包含组合和 A 和关键字数组的出现次数。我是使用 shell 脚本的新手,无法从任何逻辑开始。高度赞赏所有想法!谢谢

标签: bashshellhashmap

解决方案


如果awk可以考虑这个,你可以试试这个:

awk -F' *[AB]: *' '{a[$2","$3]++;next}END{print "A","B","Count";for(i in a){print i,a[i]}}' OFS=',' file | column -t -s','

-F选项将分隔符设置为A:B:

a填充了B字符串出现次数的数组。

END语句打印标题并循环遍历数组以打印字符串和计数。

最后命令column以表格形式显示结果。


作为对 OP 的最后更改的响应,一种可能的前进方式是使用选项定义字符串并使用regex 命令-v查找这些字符串。~

awk -F' *[AB]: *' -v h1="Hello World" -v h2="Hello" -v h3="Hi there" '$3~h1{a[$2","h1]++;next}$3~h2{a[$2","h2]++;next}$3~h3{a[$2","h3]++;next}END{print "A","Key","Count";for(i in a){print i,a[i]}}' OFS=',' file | column -t -s','

推荐阅读