bash IFS将字符串拆分为数组

时间:2015-06-12 15:52:11

标签: arrays bash ifs

我想使用filename:231:blahblah作为分隔符将以下行:拆分为数组

这是我的代码

echo "Text read from file: $line"
IFS=':' read -a FILENAME <<< $line
echo "filename: ${FILENAME[0]}"

实际输出

Text read from file: filename:231:blahblah 
filename: filename 231 blahblah

我想要的输出是

Text read from file: filename:231:blahblah 
filename: filename

我做错了什么?

1 个答案:

答案 0 :(得分:1)

解决方案1:

line="filename:231:blahblah"
IFS=':'
FILENAME=($line)
echo "filename: ${FILENAME[0]}"

解决方案2(源自您的尝试):

line="filename:231:blahblah"
IFS=':' read -a FILENAME <<< "$line"
echo "filename: ${FILENAME[0]}"

运行结果:

filename: filename