
以下を含むタブ区切りフィールドを含むテキストファイルがあります。
Baseball Korea
Badminton Spain
Soccer Germany
Baseball Korea
Badminton Spain
Badminton Korea
私がしたいのは、特定のスポーツをそのスポーツが属する国と一緒に数えることです。たとえば、バドミントンを探したいと思います。
Korea 2
Spain 3
これを行うためにawkスクリプトを使用していますが、計算に問題があります。
awk 'BEGIN {FS = '\t'} {for country in $2) if ($1 ==
'Badminton') count [$1]++} END {print (country), count
[$1]}' Sport.txt
答え1
一方通行:
$ awk 'x==$1{a[$2]++;}END{for(i in a){print i, a[i];}}' x='Badminton' file
Korea 1
Spain 2
最初の列の値が「Badminton」の場合、連想配列のカウンタをインクリメントします。そしてファイルの最後に配列の内容を印刷します。
答え2
単に。
grep Badminton <(uniq -c <(sort infile))
1 Badminton Korea
2 Badminton Spain
sort
最初は文書ですinfile
。- 次に、
uniq
各行と反復回数を印刷します。 - 最後に
grep
forパターンを作成しますBadminton
。
答え3
これにより、あなたが明示した目標を達成することができます。
awk -v sport=Badminton -F $'\t' '$1 == sport { country[$2]++ } END { for (c in country) { printf "%s\t%d\n", c, country[c] } }' Sport.txt
Sport.txt
サンプルファイルを使用した結果
Korea 1
Spain 2
説明する
# Set the awk variable 'sport' and the field separator as a tab, and read the file
awk -v sport=Badminton -F $'\t' '...code...' Sport.txt
# If the first field matches, increment the count for this country
$1 == sport { country[$2]++ }
# When there is no more input, print out each country and its count
END { for (c in country) { printf "%s\t%d\n", c, country[c] } }