0

I have string "hi how are you" I want to put this string into an array as shown below. But i want to preserve spaces. Any ideas on how to do that?

    a[0] a[1] a[2]    3   4 5   6     .... should have
     h    i   <space> h   o w <space> .... and so on.
user2404176
  • 83
  • 1
  • 1
  • 7

3 Answers3

3

One way, sure there will be better solutions but this seems to work for me:

unset arr; IFS=; for c in $(sed 's/./&\n/g' <<<"hi how are you"); do arr+=("$c"); done; echo "${arr[@]}"

It yields:

h
i

h
o
w

a
r
e

y
o
u
Birei
  • 35,723
  • 2
  • 77
  • 82
1
eval a=( $(echo "hi how are you" | sed "s/\(.\)/'\1' /g") )

It's really ugly, maybe somebody can come up with something without eval...

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
0

Probably not fast, but avoids the need for sed:

z=()
while read -n 1 x; do
    z+=( "$x" )
done <<<"hi how are you"
chepner
  • 497,756
  • 71
  • 530
  • 681