1

I have a text file, with fields separated by a tab, containing:

Baseball        Korea
Badminton       Spain            
Soccer          Germany
Baseball        Korea
Badminton       Spain
Badminton       Korea

And what I'm trying to do is count a specific sport with its country. For example i want to look up badminton so it will produce

Korea   2
Spain   3

I'm using an awk script to do so but I'm having trouble with the count

awk 'BEGIN {FS = '\t'} {for country in $2) if ($1 ==   
'Badminton') count [$1]++} END {print (country), count 
[$1]}' Sport.txt
6
  • @roaima Mac os x terminal
    – Maxxx
    Oct 19, 2017 at 8:39
  • I don't understand since Badminton appears only 1 time for Korea. In that case the solution is quite straight forward: awk '$1 == "Badminton" { c[$2]++; } END {for (a in c) print a,c[a]}' sports.txt Oct 19, 2017 at 8:44
  • @val0x00ff each column is separated by tabs. In this case should I add it before the $1 clause in your command?
    – Maxxx
    Oct 19, 2017 at 8:58
  • 1
    no but you can use this awk '$1 == "Badminton" { c[$2]++; } END {for (a in c) print a,c[a]}' OFS='\t' sports.txt where you specify that the Output Field Seperator is a tab. Oct 19, 2017 at 9:20
  • @val0x00ff that ought to be an answer rather than just written in comments. Oct 19, 2017 at 9:21

3 Answers 3

1

One way:

$ awk 'x==$1{a[$2]++;}END{for(i in a){print i, a[i];}}' x='Badminton' file
Korea 1
Spain 2

If first column value is 'Badminton', increment the counter in the associative array. And at the end of the file, print the array contents.

2
  • I'm getting an error awk: can't open file x. How is it so?
    – Maxxx
    Oct 19, 2017 at 8:35
  • @Maxxx you didn't specify OSX so Guru used a gawk construct (like I did). Use awk -v x=Badminton '...code...' file and it'll work. Oct 19, 2017 at 8:41
1

Simply.

grep Badminton <(uniq -c <(sort infile))
1 Badminton         Korea
2 Badminton         Spain
  • First sort the infile file.
  • Then uniq and print each lines and their duplicated counts.
  • Last do the grep for pattern as Badminton.
0
1

This will achieve your stated aim

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

Results using your example Sport.txt file

Korea   1
Spain   2

Explanation

# 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] } }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .