summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--functions.sh16
-rwxr-xr-xtest-functions29
2 files changed, 45 insertions, 0 deletions
diff --git a/functions.sh b/functions.sh
index 1548bd0..30c2447 100644
--- a/functions.sh
+++ b/functions.sh
@@ -514,6 +514,22 @@ 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.
#
warn()
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