Split string into an array in Bash

后端 未结 22 2200
故里飘歌
故里飘歌 2020-11-22 04:24

In a Bash script I would like to split a line into pieces and store them in an array.

The line:

Paris, France, Europe

I would like

22条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 05:08

    Sometimes it happened to me that the method described in the accepted answer didn't work, especially if the separator is a carriage return.
    In those cases I solved in this way:

    string='first line
    second line
    third line'
    
    oldIFS="$IFS"
    IFS='
    '
    IFS=${IFS:0:1} # this is useful to format your code with tabs
    lines=( $string )
    IFS="$oldIFS"
    
    for line in "${lines[@]}"
        do
            echo "--> $line"
    done
    

提交回复
热议问题