2

I am struggling earlier with a string splitting in bash. After some search i have found two method of doing this that split a string and make an array of that splitted parts.

But when i am printing them i am getting different result.

a="hello,hi,hola"

Method 1:

IFS=',' read -ra arr <<< "$a"
echo "${arr[@]}"

Output:

hello hi hola

Method 2:

arr=$(echo $a | tr "," "\n")
echo "${arr[@]}"

Output:

hello
hi
hola

What is the reason behind this?

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
  • 2
    In your method 2, `arr` is not an array. You need: `arr=( $(echo $a | tr "," "\n") )` to make it an array. Then you'll run into problems if you have consecutive space characters, or glob characters. Use Method 1, or even better, `IFS=, read -r -d '' -a arr < <(printf '%s,\0' "$a")`, which is the canonical way of splitting a string in Bash. See http://stackoverflow.com/questions/918886 . – gniourf_gniourf Sep 19 '15 at 08:58
  • You can write it as an answer with nice formatting so that fellow users might be helped. :) – Ahsanul Haque Sep 19 '15 at 09:00

1 Answers1

3

In your method 2, arr is not an array. You need:

arr=( $(echo $a | tr "," "\n") )

to make it an array.

With this method you'll run into problems if you have consecutive space characters, or glob characters. Use Method 1, or even better,

IFS=, read -r -d '' -a arr < <(printf '%s,\0' "$a")

which is the canonical way of splitting a string in Bash. See How do I split a string on a delimiter in Bash? .

Community
  • 1
  • 1
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104