bash - 使用 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 脚本的新手,无法从任何逻辑开始。高度赞赏所有想法!谢谢
解决方案
如果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','
推荐阅读
- automation - 使用 Ansible 查找和替换多行
- sas - 在SAS中的所有列上运行宏
- javascript - 从 a 中获取元素
来自 HTML 中的 svg 路径 - python - 如何在manimce中一个接一个地应用两个转换?
- mysql - JSF+Hibernate在没有spring的情况下设置admin页面权限
- python - Django 没有反向匹配,上下文破坏了我的代码
- if-statement - 是否可以在不破坏代码的情况下将 `if ... in` 和 `{` 保持在同一行?
- java - 具有同步块的类级锁定,同一实例上的多个线程
- assembly - 在 ARM 汇编中编译 MOV 指令时出错
- haskell - 如何将元组列表合并为单个元组?