2

IFS 只有一个字符,它工作正常:

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

虽然 IFS 有两个字符,但生成了额外的空格元素

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

如何摆脱数组中多余的空间元素?

4

3 回答 3

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
于 2016-10-13T04:25:53.670 回答
1

您可以将分隔符->转换为单个字符:

l="2->4->3"

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

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

如果存在字符串可能包含附加内容的风险,-则使用一个不太可能出现在字符串中的字符:

IFS="┵" read -a la <<< "${l//->/┵}"
于 2016-10-13T06:17:59.120 回答
1

我会用 sed 来替换分隔符

看,重用你的脚本+ 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

但我想我会完全不同

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

希望这可以帮助

于 2016-10-13T04:58:52.783 回答