Split string into an array in Bash

后端 未结 22 2271
故里飘歌
故里飘歌 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:01

    The accepted answer works for values in one line.
    If the variable has several lines:

    string='first line
            second line
            third line'
    

    We need a very different command to get all lines:

    while read -r line; do lines+=("$line"); done <<<"$string"

    Or the much simpler bash readarray:

    readarray -t lines <<<"$string"
    

    Printing all lines is very easy taking advantage of a printf feature:

    printf ">[%s]\n" "${lines[@]}"
    
    >[first line]
    >[        second line]
    >[        third line]
    

提交回复
热议问题