From d08033c0293942e8ce19583c73ecfc10e6ef376d Mon Sep 17 00:00:00 2001 From: Egor Tensin Date: Sun, 16 Apr 2017 06:53:12 +0300 Subject: str_split: bugfix --- %HOME%/.bash_utils/text.sh | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/%HOME%/.bash_utils/text.sh b/%HOME%/.bash_utils/text.sh index be197e1..238eb5e 100644 --- a/%HOME%/.bash_utils/text.sh +++ b/%HOME%/.bash_utils/text.sh @@ -227,16 +227,20 @@ str_split() ( fi local str="${args[0]}" - local old_delim="${args[1]}" + local delim="${args[1]}" - local -a xs - local x + if [ "${#delim}" -ne 1 ]; then + echo "${FUNCNAME[0]}: delimiter must be exactly 1 character long" >&2 + return 1 + fi - IFS="$old_delim" read -a xs -r <<< "$str" + local -a xs=() - for x in ${xs[@]+"${xs[@]}"}; do - printf -- "$fmt" "$x" - done + # Thanks to this guy for this trick: + # http://stackoverflow.com/a/24426608/514684 + IFS="$delim" read -a xs -d '' -r < <( printf -- "%s$delim\\0" "$str" ) + + [ "${#xs[@]}" -gt 0 ] && printf -- "$fmt" ${xs[@]+"${xs[@]}"} ) str_join() ( -- cgit v1.2.3