affect a exploded a string into an array

I would like to affect an exploded string into an array.

one:two::four

into an array:

a[0] => one
a[1] => two
a[2] =>
a[3] => four

Quite simple in other languages with functions like explode() or split().

The best I could come up with was this:

until [ "$token" =  "$string" ]
do
        token=${string%%:*}    # takes the first token
        a[$i]=$token           # affects the token to the array element
        string=${string#*:}    # chops that token from the string
        ((i++))
done

This return what I was looking for but I find it quite heavy for something basic.

I also tried:

a=($(echo $string | nawk -F":" '{$1=$1; print}'))

But this skips the empty tokens as it returns

a[0] => one
a[1] => two
a[2] => four

Anything more simple for such a basic thing?

#!/bin/ksh
Str=one:two::four
IFS=:
set -A Test $Str
let count=${#Test[@]}
let i=0
while [[ $i -lt $count ]]; do
print "Test[$i] ==> ${Test[$i]}"
((i=i+1))
done

Please check if this solves the problem,

Thanks
Nagarajan Ganesan

set -A arr `echo "one:two::four" | awk -F":" '{for(i=1;i<=NF;i++) print $i}'`
echo "${arr[0]}"
and so on.

@ennstate
Works fine in ksh but not in bash (I should have mentioned I was looking for a bash solution). Bash doesn't support the -A option for the set built in command. The only way I found to assign values to an array is array=(one two tree). And doing IFS=:; array=(one:two::four) doesn't work either.

@Deal_NoDeal
Also skips the empty fields as it returns
a[0] => one
a[1] => two
a[2] => four

instead of

a[0] => one
a[1] => two
a[2] =>
a[3] => four

Still trying.

In bash or ksh93:

string=one:two::four
oldIFS=$IFS
IFS=:
a=( $string )
IFS=$oldIFS

In any POSIX shell:

string=one:two::four
unset a
while :
do
  case $string in
     *:*) a[${#a[@]}]=${string%%:*}
             string=${string#*:}
             ;;
     *) a[${#a[@]}]=${string%%:*}
         break ;;
  esac
done

Works fine.

I did try changing the value of IFS but not correctly. Strange that you can assign values by doing:

a=(one two three)

But the following does not work

IFS=:
a=(one:two:three)

You have to first put the string in a variable as you did. Thank you.

If you are writing the literal values, there's no reason to use a colon:

a=( one two three )

hello every one,
I want to convert an array into list
for example the file is "agt
aag"
I need to conert it into
a
g
t
a
a
g
how I can do that in Perl?
please I need help

bioinf,

Bumping up posts or double posting is not permitted in these forums.

Please read the rules, which you agreed to when you registered, if you have not already done so.

You may receive an infraction for this. If so, don't worry, just try to follow the rules more carefully. The infraction will expire in the near future

Proceed here: I need help please

Thank You.

The UNIX and Linux Forums.