2

With only one character for IFS, it works fine:

shell@kernel: ~> l="2.4.3"; IFS="." read -a la <<< "$l"; for ((i = 0; i < ${#la[@]}; ++i)) do echo ${la[$i]}; done;
2
4
3

While there are two characters for IFS, extra space element generated

shell@kernel: ~> l="2->4->3"; IFS="->" read -a la <<< "$l"; for ((i = 0; i < ${#la[@]}; ++i)) do echo ${la[$i]}; done;
2

4

3
shell@kernel: ~> l="2..4..3"; IFS=".." read -a la <<< "$l"; for ((i = 0; i < ${#la[@]}; ++i)) do echo ${la[$i]}; done;
2

4

3

How can I get rid of the extra space element in the array?

http8086
  • 1,306
  • 16
  • 37
  • 4
    `IFS="->"` specifies field separators of `"-"` and `">"`. There is *nothing* between the `"->"` in `$l` so you get an empty element. – David C. Rankin Oct 13 '16 at 04:23
  • 3
    In other words, `IFS` is not *a* field separator. It is a list of *single-character field separators*. – larsks Oct 13 '16 at 04:28

3 Answers3

1

Continuing from the comment, you can either test for an empty element before storing the value in the array, or you can deal with the empty value when you echo it. Frankly, its simpler to do the latter, e.g.

l="2->4->3"; IFS="->" read -a la <<< "$l"; \
for ((i = 0; i < ${#la[@]}; ++i)) do \
[ -n "${la[i]}" ] && echo ${la[$i]}; done

Output

2
4
3
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
1

i would just use sed to replace the separator

see, reusing your script + sed

bash$ l="2->4->3"
bash$ read -a la <<< "$(echo $l | sed 's/->/ /g')"
bash$ for ((i = 0; i < ${#la[@]}; ++i)) do echo ${la[$i]}; done
2
4
3

but I think I would do it entirely differently

bash$ l="2->4->3"
bash$ for x in `echo $l | sed 's/->/ /g'`; do echo $x; done
2
4
3

hope this helps

Mathieu J.
  • 1,932
  • 19
  • 29
1

You could transform the separator -> into a single character with:

l="2->4->3"

IFS="-" read -a la <<< "${l//->/-}"

printf '%s' "${la[@]}"

If there is the risk that the string may contain additional - then use a character that is improbable that will be in the string:

IFS="┵" read -a la <<< "${l//->/┵}"