summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKerin Millar <kfm@plushkava.net>2024-06-03 02:21:52 +0100
committerKerin Millar <kfm@plushkava.net>2024-06-12 08:06:42 +0100
commit302084ee5cb39610378d1f963bb16adc7a78abbc (patch)
tree5736d17e10360691fa64f93594017e964b8943b1
parentAdd the oldest() and newest() functions (diff)
downloadgentoo-functions-302084ee5cb39610378d1f963bb16adc7a78abbc.tar.gz
gentoo-functions-302084ee5cb39610378d1f963bb16adc7a78abbc.tar.bz2
gentoo-functions-302084ee5cb39610378d1f963bb16adc7a78abbc.zip
Add the trim() function
As based on the implementation in Maarten Billemont's bashlib library. Signed-off-by: Kerin Millar <kfm@plushkava.net>
-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