data=$(tr -d '[]()' | tr ',' '\n')
readarray -t -n 1 group <<<"$data"
readarray -t -s 1 letters <<<"$data"
printf 'group = %s\n' "$group"
printf 'data: %s\n' "${letters[@]}"
This will first get rid of all ()
and []
from the input data that is arriving on standard input using tr
, and then it will replace the commas with newlines and assign the result to data
.
We then use readarray
to parse this data.
The first call will only read the first entry (with -n 1
) and assign it to the variable group
.
The second call to readarray
will skip the first entry (with -s 1
) and assign the remaining entries to the array letters
.
The -t
removes the actual newlines from each entry.
Even though group
is an array here, it's only containing one single element, and you may use it as $group
.
$ echo '(5,[a,b,c,d,e,f,g,h,i,j])' | bash ./script.sh
group = 5
data: a
data: b
data: c
data: d
data: e
data: f
data: g
data: h
data: i
data: j
The following retains the commas in the string and lets readline
use these to delimit the entries, but for some reason, the last element of letters
has a newline at the end:
data=$(tr -d '[]()')
readarray -d, -t -s 1 letters <<<"$data"
printf '>%s<\n' "${letters[@]}"
Running:
$ echo '(5,[a,b,c,d,e,f,g,h,i,j])' | bash ./script.sh
>a<
>b<
>c<
>d<
>e<
>f<
>g<
>h<
>i<
>j
<