首页 > 解决方案 > 如何将多字串分配到数组中

问题描述

我有以下内容的变量。

message="It's wings are too small to get its fat little body off the ground"

如何将其拆分为:

arr[0] = "It's wings"
arr[1] = "are too"
arr[2] = "small to"
arr[3] = "get its"
arr[4] = "fat little"
arr[5] = "body off"
arr[6] = "the ground"

标签: bash

解决方案


如果您想逐个读取输入并将它们存储在一个数组中,那么:

message="It's wings are too small to get its fat little body off the ground"

while read -r w1 w2 message <<< "$message"; do
    arr+=("$w1 $w2")
    [[ -z $message ]] && break
done

for (( i=0; i<${#arr[@]}; i++ )); do
    printf "arr[%d] = \"%s\"\n" "$i" "${arr[i]}"
done

输出:

arr[0] = "It's wings"
arr[1] = "are too"
arr[2] = "small to"
arr[3] = "get its"
arr[4] = "fat little"
arr[5] = "body off"
arr[6] = "the ground"

推荐阅读