bash IFS split string into array

4.8k views Asked by At

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?

1

There are 1 answers

0
Eugeniu Rosca On BEST ANSWER

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