3 ms·
If you're interested in a shell that allows to trim a string without decoding the following: trim_string() { # Usage: trim_string " example str
by xiaq 5y ago
If you're interested in a shell that allows to trim a string without decoding the following:
trim_string() {
# Usage: trim_string " example string "
: "${1#"${1%%[![:space:]]*}"}"
: "${_%"${_##*[![:space:]]}"}"
printf '%s\n' "$_"
}
You may be interested in Elvish (https://elv.sh https://elv.sh), which simply has a builtin function for trimming strings: https://elv.sh/ref/str.html#str:trim-space https://elv.sh/ref/str.html#str:trim-space
- chasil 5y agoIn a POSIX shell, I would do it like this: trim_string () ( x=${1%[:space:]} return ${x#[:space:]} ) Note the use of a subshell ( instead of command grouping { because POSIX shells do not have local function variables. At least, I think that would work. On Windows, forking is expensive, so I wouldn't do it this way.
- nomel 5y agoRelated, here's a complexity vs effort graph that I made for our company wiki: https://i.imgur.com/sGPPOhn.jpeg https://i.imgur.com/sGPPOhn.jpeg
- dncornholio 5y agoAfter reading that function, I know why I stay the heck away from bash programming.