From 302084ee5cb39610378d1f963bb16adc7a78abbc Mon Sep 17 00:00:00 2001 From: Kerin Millar Date: Mon, 3 Jun 2024 02:21:52 +0100 Subject: Add the trim() function As based on the implementation in Maarten Billemont's bashlib library. Signed-off-by: Kerin Millar --- functions.sh | 16 ++++++++++++++++ test-functions | 29 +++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/functions.sh b/functions.sh index 1548bd0..30c2447 100644 --- a/functions.sh +++ b/functions.sh @@ -513,6 +513,22 @@ srandom() srandom } +# +# Trims leading and trailing whitespace from one or more lines. If at least one +# parameter is provided, each positional parameter shall be considered as a line +# to be processed. Otherwise, the lines to be processed shall be read from the +# standard input. The trimmed lines shall be printed to the standard output. +# +trim() +{ + if [ "$#" -gt 0 ]; then + printf '%s\n' "$@" + else + cat + fi | + sed -e 's/^[[:space:]]\{1,\}//' -e 's/[[:space:]]\{1,\}$//' +} + # # Prints a diagnostic message prefixed with the basename of the running script. # diff --git a/test-functions b/test-functions index 400ddb2..bbb74f1 100755 --- a/test-functions +++ b/test-functions @@ -456,6 +456,34 @@ test_newest() { iterate_tests 4 "$@" } +test_trim() { + set -- \ + eq 0 '' '' \ + eq 0 ' ' '' \ + eq 0 ' ' '' \ + eq 0 ' X' 'X' \ + eq 0 ' X' 'X' \ + eq 0 'X ' 'X' \ + eq 0 ' X Y' 'X Y' \ + eq 0 ' X Y' 'X Y' \ + eq 0 'X Y ' 'X Y' \ + eq 0 'X Y ' 'X Y' \ + eq 0 "$(printf ' \tX')" 'X' \ + eq 0 "$(printf ' \tX\t ')" 'X' \ + eq 0 "$(printf 'X\t ')" 'X' \ + eq 0 "$(printf ' \tX Y')" 'X Y' \ + eq 0 "$(printf ' \tX Y\t ')" 'X Y' \ + eq 0 "$(printf 'X Y\t ')" 'X Y' + + callback() { + shift + test_description="trim $(_print_args "$1") (expecting $(_print_args "$2"))" + test "$(trim "$1")" = "$2" + } + + iterate_tests 4 "$@" +} + iterate_tests() { slice_width=$1 shift @@ -518,6 +546,7 @@ test_die || rc=1 test_edo || rc=1 test_srandom || rc=1 test_newest || rc=1 +test_trim || rc=1 cleanup_tmpdir -- cgit v1.2.3-65-gdbad