部分一致を使用してファイルから単語の頻度を取得します。

部分一致を使用してファイルから単語の頻度を取得します。

次のテキストファイルがあります。

tom
and
jerry
went
to
america
and
england

各単語がどのくらいの頻度で表示されるかを知りたいです。

次のコマンドを試すと

cat test.txt |sort|uniq -c

私は次のような結果を得ます。

   1 america
   2 and
   1 england
   1 jerry
   1 to
   1 tom
   1 went

しかし、部分一致も必要です。つまり、to単語に現れる単語ですtom。だから私の予想単語数toは2です。unixコマンドを使用できますか?

ベストアンサー1

以下は方法ですが、非常にエレガントではありません。

$ sort -u file | while IFS= read -r word; do 
        printf '%s\t%s\n' "$word" "$(grep -cFe "$word" file)"; 
    done
america 1
and 3
england 1
jerry   1
to  2
tom 1
went    1

おすすめ記事