1

I am looking for a way of counting the number of times a value in a field appears in a range of fields in a csv file much the same as countif in excel although I would like to use an awk command if possible.

So column 1 whould have the range of values and column 2 would have the times the value appears in column 1

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
kbiles
  • 33
  • 3

2 Answers2

1

Count how many times each value appears in the first column and append the count to the end of each line:

$ cat file
1,2,3
1,2,3
9,7,4
1,5,7
3,2,1

$ awk -F, '{c[$1]++;l[NR]=$0}END{for(i=0;i++<NR;){split(l[i],s,",");print l[i]","c[s[1]]}}' file
1,2,3,3
1,2,3,3
9,7,4,1
1,5,7,3
3,2,1,1
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
0

One more solution using Perl.

perl -F, -lane ' $kv{$F[0]}++;$kl{$.}=$_;END {for(sort keys %kl) { $x=(split(",",$kl{$_}))[0]; print "$kl{$_},$kv{$x}" }} '

Borrowing input from Chris

$ cat kbiles.txt
1,2,3
1,2,3
9,7,4
1,5,7
3,2,1

$ perl -F, -lane ' $kv{$F[0]}++;$kl{$.}=$_;END {for(sort keys %kl) { $x=(split(",",$kl{$_}))[0]; print "$kl{$_},$kv{$x}" }} ' kbiles.txt
1,2,3,3
1,2,3,3
9,7,4,1
1,5,7,3
3,2,1,1

$
stack0114106
  • 8,534
  • 3
  • 13
  • 38