split string into array in shell

Hi all,

I want to split a string into array based on given delimiter, for example:

String:

 "foo|bar|baz" 

with delimiter "|"
into array:
strArr[0] to strArr[2] with values foo, bar and baz.

Thanks a lot.
Roy987

san@~ :> declare -a myarr=(`echo "foo|bar|baz" |sed 's/|/ /g'`)
san@~ :> echo ${myarr[@]}

foo bar baz

$ cat x
#!/bin/ksh

IFS="|"
STRING="foo|bar|baz"

set -A array $STRING

print ${array[0]}
print ${array[1]}
print ${array[2]}

exit 0
$ x
foo
bar
baz
$

This led to an error "Syntax error: "(" unexpected" on my ubuntu,
I executed it in a script started with:

 #!/bin/sh 

---------- Post updated at 07:27 PM ---------- Previous update was at 07:19 PM ----------

This led to an error "Illegal option -A" on my ubuntu,
I execute it in a script started with:

 #!/bin/sh 

Maybe it is related to the mismatch of the syntax and the shell version on my machine.

Thanks a lot
Roy987

Yes I believe the Bourne shell (sh) does not support arrays. Are you able to run my complete example? Make sure to include the first line, it tells whatever your login shell is to use the korn shell to execute the script.

You may have better luck using bash (bourne again shell) heh on Linux.

1 Like

Thanks.
Actually I will ship the code to an embedded device after writing it on ubuntu, on which it is required to use Bourne Shell instead of other options, then I will try other method to pass on data.