在Bash脚本中,我希望将一行分割成多个片段,并将它们存储在一个数组中。

例如,给定一行:

Paris, France, Europe

我想让结果数组看起来像这样:

array[0] = Paris
array[1] = France
array[2] = Europe

最好是一个简单的实现;速度并不重要。我该怎么做呢?


当前回答

有时,我发现在已接受的答案中描述的方法不起作用,特别是当分隔符是回车符时。 在这些情况下,我是这样解决的:

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

其他回答

不要更改IFS!

下面是一个简单的bash一行代码:

read -a my_array <<< $(echo ${INPUT_STRING} | tr -d ' ' | tr ',' ' ')

如果你使用macOS,不能使用readarray,你可以简单地这样做-

MY_STRING="string1 string2 string3"
array=($MY_STRING)

要遍历元素:

for element in "${array[@]}"
do
    echo $element
done

另一种不修改IFS的方法是:

read -r -a myarray <<< "${string//, /$IFS}"

我们不需要更改IFS以匹配所需的分隔符,而是可以通过"${string//, /$IFS}"将所有出现的所需分隔符","替换为$IFS的内容。

也许这对于非常大的字符串来说会很慢?

这是基于Dennis Williamson的回答。

这类似于Jmoney38的方法,但是使用sed:

string="1,2,3,4"
array=(`echo $string | sed 's/,/\n/g'`)
echo ${array[0]}

打印1

试试这个

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

这很简单。如果你想,你也可以添加一个声明(并删除逗号):

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

添加IFS是为了撤销上述操作,但在新的bash实例中,它可以在没有IFS的情况下工作