|
| 1 | +#!/bin/sh |
| 2 | + |
| 3 | +# This is a tiny shell utility for string manipulation. |
| 4 | +# Allow us to use "local" |
| 5 | +# shellcheck disable=SC3043 |
| 6 | + |
| 7 | +set -eu |
| 8 | + |
| 9 | +_HELP='Usage: |
| 10 | + str {lower,upper} |
| 11 | + str test |
| 12 | +
|
| 13 | +Commands: |
| 14 | + lower, upper |
| 15 | + Convert input (stdin) to all-lowercase or all-uppercase, respectively |
| 16 | +
|
| 17 | + test <str1> (-ieq|-ine|-contains|-matches) <str2> |
| 18 | + Like "test", but with additional string comparisons: |
| 19 | + -ieq • case-insensitive equal |
| 20 | + -ine • case-insensitive not-equal |
| 21 | + -contains • Check if <str1> contains <str2> |
| 22 | + -matches • Check if <str1> matches pattern <str2> (A grep -E pattern) |
| 23 | +' |
| 24 | + |
| 25 | +fail() { |
| 26 | + # shellcheck disable=SC2059 |
| 27 | + printf -- "$@" 1>&2 |
| 28 | + printf -- "\n" 1>&2 |
| 29 | + return 1 |
| 30 | +} |
| 31 | + |
| 32 | +__str__upper() { |
| 33 | + __justStdin upper __upper "$@" |
| 34 | +} |
| 35 | +__upper() { |
| 36 | + tr '[:lower:]' '[:upper:]' |
| 37 | +} |
| 38 | + |
| 39 | +__str__lower() { |
| 40 | + __justStdin lower __lower "$@" |
| 41 | +} |
| 42 | +__lower() { |
| 43 | + tr '[:upper:]' '[:lower:]' |
| 44 | +} |
| 45 | + |
| 46 | +__justStdin() { |
| 47 | + if test $# -gt 2; then |
| 48 | + fail "Command '%s' does not take any arguments (write input into stdin)" "$1" || return |
| 49 | + fi |
| 50 | + "$2" |
| 51 | +} |
| 52 | + |
| 53 | +__str__help() { |
| 54 | + printf %s "$_HELP" |
| 55 | +} |
| 56 | +__str____help() { |
| 57 | + __str help |
| 58 | +} |
| 59 | +__str___h() { |
| 60 | + __str help |
| 61 | +} |
| 62 | +__str___help() { |
| 63 | + __str help |
| 64 | +} |
| 65 | + |
| 66 | +__str__test() { |
| 67 | + test "$#" -eq 3 || fail '“str test” expects three arguments (Got %d: “%s”)' $# "$*" \ |
| 68 | + || return |
| 69 | + local lhs="$1" |
| 70 | + local op="$2" |
| 71 | + local rhs="$3" |
| 72 | + local norm_lhs norm_rhs; |
| 73 | + norm_lhs=$(echo "$lhs" | __str lower) || return |
| 74 | + norm_rhs=$(echo "$rhs" | __str lower) || return |
| 75 | + case $op in |
| 76 | + -ieq) |
| 77 | + test "$norm_lhs" = "$norm_rhs";; |
| 78 | + -ine) |
| 79 | + test "$norm_lhs" != "$norm_rhs";; |
| 80 | + -matches) |
| 81 | + printf %s "$lhs" | grep -qE -- "$rhs";; |
| 82 | + -contains) |
| 83 | + printf %s "$lhs" | grep -qF -- "$rhs";; |
| 84 | + -*|=*) |
| 85 | + # Just defer to the underlying test command |
| 86 | + test "$lhs" "$op" "$rhs" |
| 87 | + esac |
| 88 | +} |
| 89 | + |
| 90 | +__str() { |
| 91 | + local _Command="$1" |
| 92 | + local _CommandIdent |
| 93 | + _CommandIdent="$(echo "__str__$_Command" | sed ' |
| 94 | + s/-/_/g |
| 95 | + s/\./__/g |
| 96 | + ')" |
| 97 | + shift |
| 98 | + "$_CommandIdent" "$@" |
| 99 | +} |
| 100 | + |
| 101 | +__str "$@" |
0 commit comments