Shell Script: count.sh


This shell script invokes awk to count the instances of rows in a file. A common use for this would be to pipe the file through sort before handing it to this script. For example:

cat textfile.txt | sort | ./count.sh

 

#! /bin/sh

awk '
BEGIN {
  GrandTotal=0;
  CurCount=0;
  CurVal="";
}
function report() {
  printf("%8d %s\n", CurCount, CurVal);
  GrandTotal += CurCount;
  CurCount=0;
  CurVal="";
}
(CurVal != $0) {
  if (CurCount>0) {
    report();
  }
  CurVal=$0;
}
{++CurCount}
END {
  report();
  print "======== ====================";
  CurCount=GrandTotal;
  CurVal="Grand Total";
  report();
}
'