その国に対応するテキストファイルの特定の文字列数を数えます。

その国に対応するテキストファイルの特定の文字列数を数えます。

以下を含むタブ区切りフィールドを含むテキストファイルがあります。

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各行と反復回数を印刷します。
  • 最後にgrepforパターンを作成します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] } }

関連情報