Suppose I have a Unix shell variable as below
variable=abc,def,ghij
I want to extract all the values (abc
, def
and ghij
) using a for loop and pass each value into a procedure.
The script should allow extracting arbitrary number of comma-separated values from $variable
.
If you set a different field separator, you can directly use a
for
loop:You can also store the values in an array and then loop through it as indicated in How do I split a string on a delimiter in Bash?:
Test
You can find a broader approach in this solution to How to iterate through a comma-separated list and execute a command for each entry.
Examples on the second approach:
You can use the following script to dynamically traverse through your variable, no matter how many fields it has as long as it is only comma separated.
Instead of the
echo "$i"
call above, between thedo
anddone
inside the for loop, you can invoke your procedureproc "$i"
.Update: The above snippet works if the value of variable does not contain spaces. If you have such a requirement, please use one of the solutions that can change
IFS
and then parse your variable.Hope this helps.
Try this one.
I prefer to use tr instead of sed, becouse sed have problems with special chars like \r \n in some cases.
other solution is to set IFS to certain separator
Not messing with IFS
Not calling external command
Using bash string manipulation http://www.tldp.org/LDP/abs/html/string-manipulation.html
Here is an alternative tr based solution that doesn't use echo, expressed as a one-liner.
It feels tidier without echo but that is just my personal preference.