Stuber
Stuber

Reputation: 477

awk to count occurrences and output count and output full record of last occurrence counted

I would like to count the occurrences in a single column and output counts of those occurrences along with the full record of the last occurrence counted.

This works well for counting, but would also like to have more description from the output.

awk '{count[$1]++}END{for(j in count) print j,""count[j]""}'

If input was:

A horse pen
A dog apple
B cat house
C mouse grape
C mouse shoe
C elephant pole

Output would be:

A 2 dog apple
B 1 cat house
C 3 elephant pole

Upvotes: 2

Views: 165

Answers (2)

jaypal singh
jaypal singh

Reputation: 77115

If order is critical for you then try the following with GNU awk:

awk '{
  ary[$1]++; line[$1] = $2 FS $3
}
END { 
  n = asorti(ary, sorted_ary)
  for(i = 1; i <= n; i++) {
    print sorted_ary[i], ary[sorted_ary[i]], line[sorted_ary[i]]
  }
}' file

Test:

$ cat file
A horse pen
A dog apple
B cat house
C mouse grape
C mouse shoe
C elephant pole

$    awk '{
  ary[$1]++; line[$1] = $2 FS $3
}
END { 
  n = asorti(ary, sorted_ary)
  for(i = 1; i <= n; i++) {
    print sorted_ary[i], ary[sorted_ary[i]], line[sorted_ary[i]]
  }
}' file
A 2 dog apple
B 1 cat house
C 3 elephant pole

Upvotes: 1

iruvar
iruvar

Reputation: 23364

This should work, but beware that order retention is not guaranteed

awk '{k=$1; a[k]++; $1="";
     sub(/^ +/, "", $0); b[k]=$0};
     END{for (k in a) print k, a[k], b[k]}' file.txt
A 2 dog apple
B 1 cat house
C 3 elephant pole

Upvotes: 1

Related Questions