Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash split string with delimiter ", " and keep spaces in string

Tags:

bash

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?

like image 740
user9923191 Avatar asked Sep 02 '25 11:09

user9923191


1 Answers

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")'
like image 98
anubhava Avatar answered Sep 04 '25 03:09

anubhava