LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   split a string into array in bash (http://www.linuxquestions.org/questions/linux-newbie-8/split-a-string-into-array-in-bash-869196/)

xeon123 03-17-2011 10:36 AM

split a string into array in bash
 
how do I split a string into an array?
In this string:
"this is a story"

how do I split it by the space?

Snark1994 03-17-2011 10:45 AM

Something like this should work:

Code:

#!/usr/bin/bash

IN="this is a story"

arr=$(echo $IN | tr " " "\n")

for x in $arr
do
    echo "\"$x\""
done

It should print:

Code:

"this"
"is"
"a"
"story"


grail 03-17-2011 10:46 AM

Code:

array=($(echo "this is a story"))
Edit: As it seems I was a little slow I will make an addendum to Snark's entry, if you assign the string to a variable the echo is not required at all:
Code:

IN="this is a story"

arr=($IN)


colucix 03-17-2011 10:48 AM

The blank space, which is part of the IFS shell variable, is used by default in arrays assignment:
Code:

string="this is a story"
array=($string)

Look at http://tldp.org/LDP/abs/html/arrays.html for details.

Telengard 03-17-2011 10:56 AM

Is this what you want?

Code:

~$ myArray=(this is a story)
~$ echo ${myArray[0]}
this
~$ echo ${myArray[1]}
is
~$ echo ${myArray[2]}
a
~$ echo ${myArray[3]}
story
~$

:study: Bash Reference Manual, 6.7 Arrays

Edit
Three replies before I submitted my post. I'm so slow :P

xeon123 03-17-2011 11:03 AM

My problem is that solution that you guys put here doesn't work with me and I can't understand why.

Code:

m=$(grep TOTAL_MAPS  $AVERAGEFILES | awk '{ print $2}');
echo 1 - $m
arr=$(echo $m | tr " " "\n")
echo 2 - ${arr[0]}

The output is:
Code:

1 - 90 180 90 120 120
2 - 90 180 90 120 120

As you can see, the string isn't split into an array.

Am I missing something?

grail 03-17-2011 11:13 AM

Quote:

Am I missing something?
Yes :)
Code:

arr=($(echo $m | tr " " "\n"))

xeon123 03-17-2011 11:14 AM

Here's the result with set -x enabled:

Code:

+ m='90
180
90
120
120'
+ echo 1 - 90 180 90 120 120
1 - 90 180 90 120 120
++ echo 90 180 90 120 120
++ tr ' ' '\n'
+ arr='90
180
90
120
120'
+ echo 2 - 90 180 90 120 120
2 - 90 180 90 120 120
+ set +x


xeon123 03-17-2011 11:16 AM

thanks grail, it worked.


All times are GMT -5. The time now is 04:46 AM.