Search code examples
arraysbashifs

bash IFS split string into array


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?


Solution

  • 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