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.
2
  • 1
    probably not a duplicate, most answers cannot handle spaces... Commented Jun 6, 2013 at 14:54
  • exactly. I tried to search as much as i could but couldnt find how to handle spaces.; Commented Jun 6, 2013 at 15:15

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

2 Comments

thank you Birei! I guess i am spoilt for choice ! I appreciate your response sir!
Thank you, your IFS='' trick helped me in my own problem (preserving spaces in an array of filenames)!
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...

3 Comments

do you mind explaining the sed part?
run that part alone: echo "hi how are you" | sed "s/\(.\)/'\1' /g". Replaces every character with a quoted one
silly question! should have done that! Thank you Karoly! That works! cheers!
0

Probably not fast, but avoids the need for sed:

z=()
while read -n 1 x; do
    z+=( "$x" )
done <<<"hi how are you"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.