
今日、面接官がこんな質問をしました。次の内容を含む「Myfile.txt」というファイルがあるとします。 (必ず一行にする必要はありません)
1 3 4
4 1 5
1 9 8
3 2 1
6 0 0
3 4 5
7 8 9
そのファイルに何回表示されるかを知らせるスクリプトを書いてみたいです。 0から9までの数字が含まれていることがわかります。ご覧のとおり、このファイルでは「1」が4回繰り返され、出力には「このファイルで番号1が4回使用されました」というメッセージが表示されます。
答え1
ファイルが1行に複数の数字を持つことができる場合は、まず1行に1つずつ変更してから計算する方が簡単です。たとえば、
$ tr ' ' '\n' < file| sort | uniq -c
2 0
4 1
1 2
3 3
3 4
2 5
1 6
1 7
2 8
2 9
詳細な出力が本当に必要な場合は、次のようにさらに解析できます。
$ tr ' ' '\n' < file| sort | uniq -c | while read cnt num; do printf 'The number %s appears %s times in the file\n' "$num" "$cnt"; done
The number 0 appears 2 times in the file
The number 1 appears 4 times in the file
The number 2 appears 1 times in the file
The number 3 appears 3 times in the file
The number 4 appears 3 times in the file
The number 5 appears 2 times in the file
The number 6 appears 1 times in the file
The number 7 appears 1 times in the file
The number 8 appears 2 times in the file
The number 9 appears 2 times in the file
または:
$ tr ' ' '\n' < file| sort | uniq -c | awk '{print "The number "$2" appears "$1" times in the file"}'
The number 0 appears 2 times in the file
The number 1 appears 4 times in the file
The number 2 appears 1 times in the file
The number 3 appears 3 times in the file
The number 4 appears 3 times in the file
The number 5 appears 2 times in the file
The number 6 appears 1 times in the file
The number 7 appears 1 times in the file
The number 8 appears 2 times in the file
The number 9 appears 2 times in the file
答え2
$ awk -v RS='[[:space:]]+' \
'{ n[$1]++ };
END {
for (i in n) {
print i":",n[i]
}
}' debasish.txt
(これは読みやすくするために改行とインデントが追加された1行ずつ作成されました。)
レコード区切り記号(RS
)をすべての種類のスペース(スペース、タブ、改行など)を1つ以上に設定し、配列に表示される各数を計算しますn
。n
入力が終わったら、各要素の合計を印刷します。
出力:
0: 2
1: 4
2: 1
3: 3
4: 3
5: 2
6: 1
7: 1
8: 2
9: 2