Split string into an array in Bash

后端 未结 22 2294
故里飘歌
故里飘歌 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 04:47

    Here is a way without setting IFS:

    string="1:2:3:4:5"
    set -f                      # avoid globbing (expansion of *).
    array=(${string//:/ })
    for i in "${!array[@]}"
    do
        echo "$i=>${array[i]}"
    done
    

    The idea is using string replacement:

    ${string//substring/replacement}
    

    to replace all matches of $substring with white space and then using the substituted string to initialize a array:

    (element1 element2 ... elementN)
    

    Note: this answer makes use of the split+glob operator. Thus, to prevent expansion of some characters (such as *) it is a good idea to pause globbing for this script.

提交回复
热议问题