I am having a string with the value:
str="name1, name2, name3, "
I want to traverse the list of elements. How do I loop them?
I am having a string with the value:
str="name1, name2, name3, "
I want to traverse the list of elements. How do I loop them?
One way:
$ cat sloop
#! /usr/bin/ksh
str="name1, name2, name3, "
while [[ -n $str ]] ; do
item=${str%%,*}
str=${str#* }
echo item = $item
done
exit 0
$ ./sloop
item = name1
item = name2
item = name3
Its easy to loop a string with spaces. So u can substitute the , with a space and then use that new string to loop using for....
str1="value1,value2,value3"
str2=`echo $str1 | tr "," " "`
#there is a space in between the second pair of quotes
for text in $str2
do
echo "$text"
done
Thanks Perderabo and Justsam.
Justsam logic seems to be bit easy.
Perderabo logic is not working if we have no space in str
str="name1,name2,name3, "
Here's my favorite way of doing this, similar to justsam but without piping $str through tr (UUOtr
)
str="name1, name2, name3, "
typeset IFS=' ,'
for i in $str
do
echo $i$i
done
Yeah but your original post had ", " which is two characters and there is a superfluous separator ending the string. Sorry for believing what you wrote was accurately describing your problem. ![]()
str="name1,name2,name3, "
typeset IFS=' ,'
for i in $str
do
echo $i
done
works with both ", " and ","