Browse Source

Adicionar 'cawk'

main
Blau Araujo 1 year ago
parent
commit
c0f9a3089d
  1. 113
      cawk

113
cawk

@ -0,0 +1,113 @@
#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# Script : cawk
# Descrição: REPL calculator in bash and GNU AWK.
# Versão : 0.0.1
# Data : 09/03/2022
# Licença : GNU/GPL v3.0
# -----------------------------------------------------------------------------
# Copyright (C) 2022 Blau Araujo <blau@debxp.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# -----------------------------------------------------------------------------
# USAGE
# cawk [-f PRECISION] - Start in REPL mode.
# cawk -e EXPRESSION [-f PRECISION] - Eval EXPRESSION and quit.
# COMMAND | cawk [-f PRECISION] - Eval expressions from COMMAND output.
# -----------------------------------------------------------------------------
version="0.0.1"
error[0]="Exiting..."
error[1]="Invalid expression!"
error[2]="Invalid argument!"
help="cawk ($version) - REPL calculator in Bash and AWK
USAGE
cawk [-f PRECISION] - Start in REPL mode.
cawk -e EXPRESSION [-f PRECISION] - Eval EXPRESSION and quit.
COMMAND | cawk [-f PRECISION] - Eval expressions from COMMAND output.
OPTIONS
-e EXPRESSION Expression to evaluate.
-f PRECISION Number of positions after decimal point.
COMMANDS
f[0-9] Redefine precision.
h|? Help.
q|quit Quit.
"
# functions -------------------------------------------------------------------
shopt -s extglob
die() {
(($1)) && echo "$help"
printf '\e[33;1m%s\e[m\n' "${error[$1]}"
exit $1
}
calc() {
local exp fix
exp="$1"
fix=$2
awk 'BEGIN {
printf "%.'$fix'f\n", ('"$exp"')
}' 2> /dev/null || die 1
}
repl() {
while :; do
read -erp ': '
history -s "$REPLY"
case "${REPLY,,}" in
f*( )+([0-9])) PRECISION=${REPLY:1} ;;
h|'?') echo "$help" ;;
q|quit) die 0 ;;
*) calc "$REPLY" $PRECISION;;
esac
done
}
opts() {
local param
for param; do
case $param in
-h|--help) echo "$help"; exit ;;
-e) EXPRESSION=${@:2:1} ;;
-e?*) EXPRESSION=${param:2};;
-f) PRECISION=${@:2:1} ;;
-f?*) PRECISION=${param:2} ;;
esac
shift
done
}
# main ------------------------------------------------------------------------
unset EXPRESSION
PRECISION=2
opts "$@"
if [[ -t 0 ]];then
[[ $EXPRESSION ]] && { calc "$EXPRESSION" $PRECISION; exit; }
repl $PRECISION
else
while read; do
calc "$REPLY" $PRECISION
done
fi
Loading…
Cancel
Save