In a Bash script I would like to split a line into pieces and store them in an array.
The line:
Paris, France, Europe
I would like
Since there are so many ways to solve this, let's start by defining what we want to see in our solution.
readarray
for this purpose. Let's use it.IFS
, looping, using eval
, or adding an extra element then removing it.The readarray
command is easiest to use with newlines as the delimiter. With other delimiters it may add an extra element to the array. The cleanest approach is to first adapt our input into a form that works nicely with readarray
before passing it in.
The input in this example does not have a multicharacter delimiter. If we apply a little common sense, it's best understood as comma separated input for which each element may need to be trimmed. My solution is to split the input by comma into multiple lines, trim each element, and pass it all to readarray
.
string=' Paris,France , All of Europe '
readarray -t foo < <(tr ',' '\n' <<< "$string" |sed 's/^ *//' |sed 's/ *$//')
declare -p foo
# declare -a foo='([0]="Paris" [1]="France" [2]="All of Europe")'