linux - 如何使用 bash 脚本计算一个单词中出现的最多 3 个字母的序列
问题描述
Indo Cheap 有一个示例文件,例如
XYZAcc
ABCAccounting
Accounting firm
Accounting Aco
Accounting Acompany
Acoustical consultant
他需要得到一个单词中出现次数最多的 3 个字母序列。
输出应该是
acc = 5 aco = 3
他问这在 bash 中是否可行。
他说:“我完全不知道如何使用 awk、sed 和 grep 来完成它。
任何线索怎么可能……”
解决方案
使用 bash、sed 和 awk 绝对可以做到这一点,这里是如何做到的:
#!/bin/bash
for line in $(cat sample | tr 'A-Z' 'a-z' | tr -s ' ' '\n'); do
ll=${#line}
for ((i = 0; i < ll - 2; i++)) ; do # for each word
echo ${line:i:3} # print all sequences of 3 letters
done
done |
sort | # sort the sequences of three letters
uniq -c | # count the sequences
sed '/^ *1 /d' | # filter out the not repeated sequences
sort -n -r | # most frequent sequences first
awk -F ' ' '{print $2" = "$1}' | # format output as asked
tr '\n' ' ' # put all results on one line
echo # add a new line at the end
上面示例的输出是:
cou = 5 acc = 5 unt = 4 tin = 4 oun = 4 nti = 4 ing = 4 cco = 4 aco = 3
如果需要其他格式的输出,我们可以根据需要轻松调整脚本代码。
推荐阅读
- c# - 条码扫描不允许用户移动条码扫描两次
- asp.net-core - Razor Pages 中 wwwroot 下静态文件的路径
- algorithm - 在 n 次旋转后查找索引处的元素
- javascript - Electron 在操作系统中创建实际的鼠标点击
- vba - url不规范时上传文件在线分享点
- javascript - 仅允许 JavaScript 中选定的 UTF 语言输入,并在服务器端验证它
- ruby-on-rails - 如何覆盖belongs_to getter?
- java - 从操作栏菜单项单击调用活动
- javascript - React-js 如何触发“BeforeInstallPromptEvent”以启动“弹出”添加到主屏幕
- node.js - NodeJS 使用回调来等待 foreach 的结束