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 to have them in an array like this:
array[0] = Paris
array[1] = France
array[2] = Europe
I would like to use simple code, the command's speed doesn't matter. How can I do it?
Sometimes it happened to me that the method described in the accepted answer didn't work, especially if the separator is a carriage return.
In those cases I solved in this way:
Use this:
The key to splitting your string into an array is the multi character delimiter of
", "
. Any solution usingIFS
for multi character delimiters is inherently wrong since IFS is a set of those characters, not a string.If you assign
IFS=", "
then the string will break on EITHER","
OR" "
or any combination of them which is not an accurate representation of the two character delimiter of", "
.You can use
awk
orsed
to split the string, with process substitution:It is more efficient to use a regex you directly in Bash:
With the second form, there is no sub shell and it will be inherently faster.
Edit by bgoldst: Here are some benchmarks comparing my
readarray
solution to dawg's regex solution, and I also included theread
solution for the heck of it (note: I slightly modified the regex solution for greater harmony with my solution) (also see my comments below the post):Another way would be:
Now your elements are stored in "arr" array. To iterate through the elements: