bash - 如何将多字串分配到数组中
问题描述
我有以下内容的变量。
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"
解决方案
如果您想逐个读取输入并将它们存储在一个数组中,那么:
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"
推荐阅读
- migration - 如何将 jira 的 sprint 迁移到 Azure DevOps?
- c# - 使用 httpclient 将 curl 命令转换为 C# 代码
- mongodb - 连接到 AWS 上的 DocumentDB/MongoDB 实例时出现问题
- javascript - 如何获取时刻时区当前配置的时区?
- python - 子类化一个python类来改变初始化器是最好的模式吗?
- javascript - 如何使用 sequelize 和节点插入由多个对象组成的数组?
- ios - Objective-C 数据类型问题
- postgresql - 完全重新安装后 psql 无法连接到服务器 [Ubuntu 21.10 / PostgreSQL 13]
- android - drawableLeft图标和文本之间的Android MaterialButton填充
- python - Pymongo update_many 没有为地理空间过滤器添加新字段