I already read How to split a string into an array in bash but the question seems a little different to me so I'll ask using my data.
I have this line comming from STDIN :
(5,[a,b,c,d,e,f,g,h,i,j])
The five is my group ID and the letters are values of an array (the group data).
I need to get the group ID into a var and the letters into something I can work using IFS=',' read -r -a array <<< "$tline"
Best Answer
Explanations:
bkpIFS="$IFS"
;Then we set IFS to set of delimiters
,
,(
,)
,]
and[
withIFS=',()]['
which means our input string can be delimited with one-or-more of these delimiters.Next
read -r -a array
reads and split the line into an array calledarray
only based on defined IFS above from input string passed in Here-String method. The-r
option is used to tellread
command don't does expansion on back-slash\
if come in input.see the last
,k
which it caused by having back-slash in input andread
without its-r
option.With
echo ${array[@]}
we are printing all elements of array. see What is the difference between $* and $@? and Gilles's answer about${array[@]}
there with more details.With
printf "%s\n" ${array[@]}
also there is other approach to printing array elements.Now you can print a specific element of array with
printf "%s\n" ${array[INDEX]}
or same withecho ${array[INDEX]}
.Ah, sorry, forgot to give
IFS
back to shell,IFS="$bkpIFS"
: )Or using
awk
and itssplit
function.Explanations:
Same here, we are splitting the entire line of input based on defined group of delimiters
[...]
in regexp constant/[...]/
which support in modern implementation ofawk
usingsplit
function. read more in section ofsplit()
function.Next at the
END{for (x in arr) printf ("%s ",arr[x]); ...}
we are looping over array calledarr
and print their corresponding value.x
here point to the index of arrayarr
elements. read more aboutawk
's BEGIN/END rules.Side-redirect to How to add/remove an element to the array in bash?.