Bash Script: Histogram

Second bash script of the day!  This one will histogram the field of a given CSV file numerically.  Optionally, you can specify which field and a precision (which is really just a number of characters, not truly a precision).

histogram() {
  if [ $# -lt 1 ]
  then
    echo "Usage: histogram  [field] [precision]"
    return 0
  fi

  field=1
  if [ $# -gt 1 ]
  then
   field=$2
  fi

  if [ $# -gt 2 ]
  then
    precision="."
    for i in `seq 1 1 $3`
    do
      precision=$precision.
    done

    cat $1 | sort -k $field -n -t ',' | cut -d ',' -f $field | sed -e "s/\($precision\).*/\1/" | uniq -c
  else
    cat $1 | sort -k $field -n -t ',' | cut -d ',' -f $field | uniq -c
  fi
}
This entry was posted in Uncategorized. Bookmark the permalink.