首页 > 解决方案 > 如何使用 bash 脚本计算一个单词中出现的最多 3 个字母的序列

问题描述

Indo Cheap 有一个示例文件,例如

XYZAcc
ABCAccounting
Accounting firm
Accounting Aco
Accounting Acompany
Acoustical consultant

他需要得到一个单词中出现次数最多的 3 个字母序列。

输出应该是

acc = 5 aco = 3

他问这在 bash 中是否可行。

他说:“我完全不知道如何使用 awk、sed 和 grep 来完成它。

任何线索怎么可能……”

标签: linuxbashawksed

解决方案


使用 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

如果需要其他格式的输出,我们可以根据需要轻松调整脚本代码。


推荐阅读