Created
January 30, 2020 10:32
-
-
Save x3rAx/9150ee1984d13f9553f17dad80a741bd to your computer and use it in GitHub Desktop.
Trim whitespaces from a string with pure bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trim_l() { | |
local str="$1" | |
if [[ $str =~ ^[[:space:]]*(|[^[:space:]].*)$ ]]; then | |
str="${BASH_REMATCH[1]}" | |
fi | |
echo "$str" | |
} | |
trim_r() { | |
local str="$1" | |
if [[ $str =~ ^(|.*[^[:space:]])[[:space:]]*$ ]]; then | |
str="${BASH_REMATCH[1]}" | |
fi | |
echo "$str" | |
} | |
trim() { | |
local str="$1" | |
if [[ $str =~ ^[[:space:]]*(|[^[:space:]]|[^[:space:]].*[^[:space:]])[[:space:]]*$ ]]; then | |
str="${BASH_REMATCH[1]}" | |
fi | |
echo "$str" | |
} | |
result_ok=0 | |
result_fail=0 | |
test() { | |
local method="$1" | |
local test_data="$2" | |
local expected="$3" | |
local result="$($method "$test_data")" | |
if [[ $result == $expected ]]; then | |
echo "OK: ${method}: |${test_data}| => |${result}|" | |
let result_ok++ | |
return | |
fi | |
echo "FAIL: ${method}: |${test_data}| => |${result}| (expected: |${expected}|)" | |
let result_fail++ | |
return 1 | |
} | |
test trim "" "" | |
test trim_l "" "" | |
test trim_r "" "" | |
echo "" | |
test trim "a" "a" | |
test trim_l "a" "a" | |
test trim_r "a" "a" | |
echo "" | |
test trim "ab" "ab" | |
test trim_l "ab" "ab" | |
test trim_r "ab" "ab" | |
echo "" | |
test trim "abc" "abc" | |
test trim_l "abc" "abc" | |
test trim_r "abc" "abc" | |
echo "" | |
test trim "abcd" "abcd" | |
test trim_l "abcd" "abcd" | |
test trim_r "abcd" "abcd" | |
echo "" | |
test trim " abcd" "abcd" | |
test trim_l " abcd" "abcd" | |
test trim_r " abcd" " abcd" | |
echo "" | |
test trim "abcd " "abcd" | |
test trim_l "abcd " "abcd " | |
test trim_r "abcd " "abcd" | |
echo "" | |
test trim " abcd " "abcd" | |
test trim_l " abcd " "abcd " | |
test trim_r " abcd " " abcd" | |
echo "" | |
test trim " ab cd " "ab cd" | |
test trim_l " ab cd " "ab cd " | |
test trim_r " ab cd " " ab cd" | |
echo "" | |
test trim " ab x y cd " "ab x y cd" | |
test trim_l " ab x y cd " "ab x y cd " | |
test trim_r " ab x y cd " " ab x y cd" | |
echo "" | |
echo "Result:" | |
echo " OK: ${result_ok}" | |
echo " FAIL: ${result_fail}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment