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?
Here is a way without setting IFS:
The idea is using string replacement:
to replace all matches of $substring with white space and then using the substituted string to initialize a array:
Note: this answer makes use of the split+glob operator. Thus, to prevent expansion of some characters (such as
*
) it is a good idea to pause globbing for this script.Prints three
Another way to do it without modifying IFS:
Rather than changing IFS to match our desired delimiter, we can replace all occurrences of our desired delimiter
", "
with contents of$IFS
via"${string//, /$IFS}"
.Maybe this will be slow for very large strings though?
This is based on Dennis Williamson's answer.
Another approach can be:
After this 'arr' is an array with four strings. This doesn't require dealing IFS or read or any other special stuff hence much simpler and direct.
Try this
It's simple. If you want, you can also add a declare (and also remove the commas):
The IFS is added to undo the above but it works without it in a fresh bash instance
Pure bash multi-character delimiter solution.
As others have pointed out in this thread, the OP's question gave an example of a comma delimited string to be parsed into an array, but did not indicate if he/she was only interested in comma delimiters, single character delimiters, or multi-character delimiters.
Since Google tends to rank this answer at or near the top of search results, I wanted to provide readers with a strong answer to the question of multiple character delimiters, since that is also mentioned in at least one response.
If you're in search of a solution to a multi-character delimiter problem, I suggest reviewing Mallikarjun M's post, in particular the response from gniourf_gniourf who provides this elegant pure BASH solution using parameter expansion:
Link to cited comment/referenced post
Link to cited question: Howto split a string on a multi-character delimiter in bash?