各数の発生回数を計算します。

各数の発生回数を計算します。

ファイルには5つの数値列が含まれています。

例:

12 34 67 88 10
 4 90 12 10 7
33 12 5  76 34

同じ数字を印刷して何回印刷されるかを確認したい。例:

3 : 12
2 : 34

ベストアンサー1

このawkスクリプトは、例に示すように出力を印刷します。

awk '{ 
         for ( i=1; i<=NF; i++ ) # loop over all fields/columns
            dict[$i]++;      # count occurrence in an array using the field value as index/key
     }
 END {                           # after processing all data
         for (key in dict)       # iterate over all array keys
             if(dict[key]>1)     # if the key occurred more than once
                 print dict[key] " : " key    # print counter and key
     }' inputfile

たとえば、入力、出力は次のようになります。

2 : 10
3 : 12
2 : 34

条件を削除すると、if(a[i]>1)一度だけ表示される番号も一覧表示されます。

発生回数の降順で結果を並べ替えるには、次を追加します。

| sort -nr

これは、数値の逆順にソートすることを意味します。

したがって、awk上記のコマンドはソートと組み合わせられます。

awk '...' inputfile | sort -nr

生産する

3 : 12
2 : 34
2 : 10

forGlenn jackmanのコメントで述べたように、PROCINFO["sorted_in"] = "@val_num_desc"ブロックの上にを追加して処理中に配列値をソートするようにGNU AWKに指示できますEND

 END {                           # after processing all data
         # In GNU AWK only you can use the next line to sort the array for processing
         PROCINFO["sorted_in"] = "@val_num_desc" # sort descending by numeric value
         for (key in dict)       # iterate over all array keys
             if(dict[key]>1)     # if the key occurred more than once
                 print dict[key] " : " key    # print counter and key
     }

このGNU固有の拡張機能を使用するとsort

おすすめ記事