I have a variable in a bash script that I want to split into an array, with ", " as the delimiter. This is my code:
#!/bin/sh
food="cookies, ice cream, candy, candy cane"
IFS=", "
read -ra array <<< "$food"
for element in "${array[@]}"
do
echo "$element"
done
I have seen this post, but as Dennis said, bash will use both "," and " " separately. So then when I run it, "ice" and "cream" are on separate lines, and so are "candy" and "cane" because bash is also treating " " as a delimiter (at least I think that's the reason).
cookies
ice
cream
candy
candy
cane
How do I split the string so that the spaces in "ice cream" and "candy cane" are left there?
I don't think it matters, but I am on OS X. I used #!/bin/sh
, but I tried #!/bin/bash
and got the same result; they should be the same...should they?
You can do a bit of processing in input to replace all ", "
with ","
before reading it into array:
food="cookies, ice cream, candy, candy cane"
IFS=, read -ra array <<< "${food//, /,}"
declare -p array
declare -a array='([0]="cookies" [1]="ice cream" [2]="candy" [3]="candy cane")'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With