2

I have the following line filename:231:blahblah that I want to split into an array using : as the delimiter

The is the code that I have

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

actual output is

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

The output I want is

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

What am I doing wrong?

Sahar Rabinoviz
  • 1,939
  • 2
  • 17
  • 28
  • Quote `$line` when reading into array => `read -a FILENAME <<< "$line"` – Eugeniu Rosca Jun 12 '15 at 16:12
  • You aren't doing anything wrong. There is a bug in `bash`, fixed in version 4.3, that causes the `IFS` setting to be incorrectly mixed with the parameter expansion in the here string. – chepner Jun 12 '15 at 16:13
  • @chatraed When `bash` works correctly, the quotes aren't necessary. A single parameter expansion doesn't undergo word-splitting when it is the argument of the here-string operator. – chepner Jun 12 '15 at 16:16
  • @chepner: thanks, you always provide crystal clear explanations. – Eugeniu Rosca Jun 12 '15 at 16:20

1 Answers1

1

Solution 1:

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

Solution 2 (derived from your try):

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

Run result:

filename: filename
Eugeniu Rosca
  • 5,177
  • 16
  • 45