On 2020-07-14 21:52, Albretch Mueller wrote:
I have a string delimited by two characters: "\|"
_S=" 34 + 45 \| abc \| 1 2 3 \| c\|123abc "
which then I need to turn into a array looking like:
_S_AR=(
" 34 + 45"
" abc"
" 1 2 3"
" c"
"123abc"
)
Is it possible to do such things in bash?
Yes, if you don't mind running a loop.
This method cuts off the first part of the string, up to the delimiter,
and adds it to the array, then continues with what's left of the string
until there's none left:
---
#!/bin/bash
_S=' 34 + 45 \| abc \| 1 2 3 \| c\|123abc '
del='\|'
arr=()
s=${_S}${del}
while [[ -n $s ]]
do
arr+=( "${s%%"${del}"*}" )
s=${s#*"${del}"}
done
declare -p arr
---
outputs:
declare -a arr=([0]=" 34 + 45 " [1]=" abc\\ " [2]=" 1 2 3 " [3]=" c"
[4]="123abc ")
I've used this myself, so am eager to hear of any hidden snags. :)
(One already: if the delimiter is a repeated character which might also
be the last in the last string fragment, then the loop never closes.
Fairly rare?)
Originally found here:
https://www.tutorialkart.com/bash-shell-scripting/bash-split-string/
--
John