LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Accessing arrays position in a split string (http://www.linuxquestions.org/questions/linux-newbie-8/accessing-arrays-position-in-a-split-string-867714/)

xeon123 03-10-2011 10:12 AM

Accessing arrays position in a split string
 
Hi,

I've a string "this.is.a.name", and I would like to put it in an array.
But, I've like to print the output of the array as:

Code:

echo ${array[0]}
echo ${array[1]}
echo ${array[2]}
echo ${array[3]}

I've tried with

Code:

STR="this.is.a.name";
arr=$(echo $STR | tr "." " ");

echo ${array[0]}
echo ${array[1]}
echo ${array[2]}
echo ${array[3]}

but only the first position contains the phrase "this is a name". The rest of the array is empty.

I've searched over the manuals and the web, and I couldn't find a solution for my case.

How can I do that?

Thanks,

Guttorm 03-10-2011 10:18 AM

You're close, but you need to add another set of () when you assign the array.

Code:

#!/bin/bash
STR="this.is.a.name"
array=($(echo $STR | tr "." " "))
echo ${array[0]}
echo ${array[1]}
echo ${array[2]}
echo ${array[3]}


xeon123 03-10-2011 10:20 AM

That's right Guttorm, but what's the meaning of the outer parenthesis of "($(echo $STR | tr "." " "))"?

Guttorm 03-10-2011 10:25 AM

Without the outer, the variable named array simply gets the value of "this is a name". The outer means it will be an array. The difference is the same as

array="this is a name"
array=(this is a name)

xeon123 03-10-2011 10:36 AM

Now I get it. Thanks for the help.


All times are GMT -5. The time now is 11:01 AM.