Split string into an array in Bash

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

    Try this

    IFS=', '; array=(Paris, France, Europe)
    for item in ${array[@]}; do echo $item; done
    

    It's simple. If you want, you can also add a declare (and also remove the commas):

    IFS=' ';declare -a array=(Paris France Europe)
    

    The IFS is added to undo the above but it works without it in a fresh bash instance

提交回复
热议问题