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
Another way to do it without modifying IFS:
read -r -a myarray <<< "${string//, /$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.
Use this:
countries='Paris, France, Europe'
OIFS="$IFS"
IFS=', ' array=($countries)
IFS="$OIFS"
#${array[1]} == Paris
#${array[2]} == France
#${array[3]} == Europe
if you use macOS and can't use readarray, you can simply do this-
MY_STRING="string1 string2 string3"
array=($MY_STRING)
To iterate over the elements:
for element in "${array[@]}"
do
echo $element
done
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:
string='first line
second line
third line'
oldIFS="$IFS"
IFS='
'
IFS=${IFS:0:1} # this is useful to format your code with tabs
lines=( $string )
IFS="$oldIFS"
for line in "${lines[@]}"
do
echo "--> $line"
done