Search code examples
linuxbashsplitifs

Split string with IFS using Bash?


I have a string like:

Spain-South Africa:2-1

And I want to split it like:

Spain-South Africa
2-1

I have tried to split it by IFS=':' but it gives me:

Spain-South

Africa
2-1

My code:

code


Solution

  • Cannot reproduce, but you are probably either not setting IFS correctly for the read command, or you are not displaying the output correctly.

    $ str="Spain-South Africa:2-1"
    $ IFS=: read -ra results <<< "$str"
    $ declare -p results
    declare -a results=([0]="Spain-South Africa" [1]="2-1")
    

    Based on your short-lived comment, you want something like

    while IFS=: read -ra results; do
        ...
    done < "$1"
    

    rather than

    for str in $(cat "$1"); do
        ...
    done