Extracting the values separated by comma

Hi,

I have a variable which has a list of string separated by comma.

for ex ,

Variable=/usr/bin,/usr/smrshbin,/tmp

How can i get the values between the commas separately using shell scripts.Please help me.

Thanks,
Padmini.

try..

-bash-3.2$ Variable=/usr/bin,/usr/smrshbin,/tmp
-bash-3.2$ echo $Variable | awk -F, '{print $1,$2}'
/usr/bin /usr/smrshbin
-bash-3.2$ echo $Variable | awk -F, '{print $1}'
/usr/bin
-bash-3.2$ echo $Variable | awk -F, '{print $1,$2,$3}'
/usr/bin /usr/smrshbin /tmp
-bash-3.2$

Hi,

Thanks for the reply.But in this case , i dont know the no of string values(for the above case it is 3 but actual case it is not fixed) i will be getting.How can i handle that?

try this.

-bash-3.2$ echo $Variable
/usr/bin,/usr/smrshbin,/tmp,/tmp,/opt,/test
-bash-3.2$ echo $Variable | awk -F, '{ for (i = 1; i < NF; ++i ) print $i }'
/usr/bin
/usr/smrshbin
/tmp
/tmp
/opt
-bash-3.2$

oops last field missing just replace with "i <= NF"

You can also use an array (bash version) :

var=/usr/bin,/usr/smrshbin,/tmp,/tmp,/opt,/test
IFS=, paths=($var)
for (( i=0; i<${#paths[@]}; i++ ))
do
   echo "[$i] ${paths[$i]}"
done

Output:

[0] /usr/bin
[1] /usr/smrshbin
[2] /tmp
[3] /tmp
[4] /opt
[5] /test

Jean-Pierre.

Thanks for the reply.

---------- Post updated at 12:41 PM ---------- Previous update was at 12:24 PM ----------

Hi,
Depending on the above output, i need to assign the separated values to variables by dynamically creating them . how is that possible?

You can assign it to array, which was already answered by Jean-Pierre.
Here's my method though

-bash-3.2$ array=(`echo $Variable | sed 's/,/\n/g'`)
-bash-3.2$ echo ${array[0]}
/usr/bin
-bash-3.2$ echo ${array[1]}
/usr/smrshbin
-bash-3.2$ echo ${array[2]}
/tmp