bin/props @ 41849d4b8593

More
author Steve Losh <steve@stevelosh.com>
date Tue, 28 Nov 2023 16:23:43 -0500
parents d9ee2c4aa85b
children (none)
#!/usr/bin/env bash

set -euo pipefail

function usage {
    echo "props - display proportions of stdin, bucketed by unique lines

USAGE: $0 [OPTIONS]

Options:
  -h, --help          display this help text and exit
  -p, --percent       display proportions as percentages
  -P, --no-percent    display proportions as values from 0 to 1 (default)
  -d N, --decimals N  how many decimal places to display in the result
"
}

function die {
    echo "$0: $1" >&2
    exit 1
}

OPTS=$(getopt --options hd:pP --long help,decimals:,percent,no-percent -n "$0" -- "$@")
eval set -- "$OPTS"

DECIMALS='5'
MUL='1.0'

while test "$#" -gt 0; do
    case "$1" in
        -h | --help )       usage; exit 0 ;;
        -d | --decimals )   DECIMALS="$2"; shift 2 ;;
        -p | --percent )    MUL='100.0';   shift ;;
        -P | --no-percent ) MUL='1.0';     shift ;;
        -- ) shift; if test "$#" -ne 0; then die "unrecognized arguments: $*"; fi ;;
        * ) die "unrecognized arguments: $*" ;;
    esac
done

awk '
    { c[$0]++ }
END { for (l in c) printf("%.'"$DECIMALS"'f %s\n", c[l] / NR * '"$MUL"', l) }
'