2013-03-22 13 views
6

Ho una stringascript Bash per convertire una stringa con spazio delimitato gettoni per un array

echo $STRING 

che dà

first second third fourth fifth 

fondamentalmente un elenco separato spazi.

Come faccio a prendere quella stringa e renderlo una matrice in modo che

array[0] = first 
array[1] = second 

ecc ..

ho cercato

IFS=' ' read -a list <<< $STRING 

ma poi quando faccio un

echo ${list[@]} 

stampa solo o ut "prima" e nient'altro

+0

Vedi qui: http://stackoverflow.com/questions/918886/how-do-i-split-a-string-on -a-delimiter-in-bash – ceving

risposta

11

E 'semplice realtà:

list=($STRING) 

O più verboso:

declare -a list=($STRING) 

PS: Non è possibile esportare IFS e utilizzare il nuovo valore nello stesso comando . Si deve dichiarare per primo, poi usare i suoi effetti nel seguente comando:

$ list=(first second third) 
$ IFS=":" echo "${list[*]}" 
first second third 
$ IFS=":" ; echo "${list[*]}" 
first:second:third 
+0

fantastico che ha funzionato. Ma come fa a sapere cosa dividerlo? – Dan

+0

Il valore predefinito di 'IFS' 'è' \ t \ n \ r' o qualcosa del genere. Quando si assegna a un array usando '()' -syntax, tutto ciò che si trova tra parentesi viene espanso come i parametri di un comando, trasformando ogni "parametro" in un elemento dell'array. – svckr

Problemi correlati