単語を含む行数の計算

単語を含む行数の計算

複数行を含むファイルがあります。ファイル全体に表示される各単語について、その単語を含む行数を知りたいです。たとえば、次のようになります。

0 hello world the man is world
1 this is the world
2 a different man is the possible one

私が期待する結果は次のとおりです。

0:1
1:1
2:1
a:1
different:1
hello:1
is:3
man:2
one:1
possible:1
the:3
this:1
world:2

「world」の数は3ではなく2です。単語が2行に現れるからです。したがって、スペースを改行に変換することは正確な​​解決策ではありません。

ベストアンサー1

別のPerlバリアント、使用リスト::ユーティリティ

$ perl -MList::Util=uniq -alne '
  map { $h{$_}++ } uniq @F }{ for $k (sort keys %h) {print "$k: $h{$k}"}
' file
0: 1
1: 1
2: 1
a: 1
different: 1
hello: 1
is: 3
man: 2
one: 1
possible: 1
the: 3
this: 1
world: 2

おすすめ記事