首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ash中使用数组?

如何在ash中使用数组?
EN

Stack Overflow用户
提问于 2015-03-27 15:18:56
回答 1查看 9.4K关注 0票数 7

由于某些原因,我不能使用bash来构建我的脚本,唯一的方法是使用ash,我有这个短信自动回复脚本,每个回复必须是最多160个字符的长度,它看起来是这样的:

代码语言:javascript
复制
#!/bin/sh
    reply="this is a reply message that contains so many words so I have to split it to some parts"
    array="${reply:0:5} ${reply:5:5} ${reply:10:5} ${reply:15:5} ${reply:20:5}"
    for i in $array
    do
    echo "send sms with the message: $i"
    done

但它最终是这样的:

代码语言:javascript
复制
send sms with the message: this
send sms with the message: is
send sms with the message: a
send sms with the message: reply
send sms with the message: mess
send sms with the message: age
send sms with the message: t

我想要的是这样的:

代码语言:javascript
复制
send sms with the message: this 
send sms with the message: is a 
send sms with the message: reply
send sms with the message: messa
send sms with the message: ge th
send sms with the message: at co
send sms with the message: ntain

所以它是按字符数拆分,而不是按单词拆分,我该怎么做呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-27 15:34:19

您的数组实际上不是一个数组,但请阅读http://mywiki.wooledge.org/WordSplitting以了解有关这方面的更多信息。

ash本身并不支持数组,但您可以通过使用set来规避这一点

代码语言:javascript
复制
reply="this is a reply message that contains so many words so I have to split it to some parts"
set -- "${reply:0:5}" "${reply:5:5}" "${reply:10:5}" "${reply:15:5}" "${reply:20:5}"
for i; do
        echo "send sms with the message: $i"
done

-

代码语言:javascript
复制
send sms with the message: this
send sms with the message: is a
send sms with the message: reply
send sms with the message:  mess
send sms with the message: age t

对此有许多替代解决方案,其中之一是使用fold为您完成拆分工作,并增加了一个优点,即它可以在空格上换行,使消息更具可读性(请参阅man fold了解更多信息):

代码语言:javascript
复制
reply="this is a reply message that contains so many words so I have to split it to some parts"
echo "${reply}" | fold -w 10 -s | while IFS= read -r i; do
        echo "send sms with the message: $i"
done

-

代码语言:javascript
复制
send sms with the message: this is a
send sms with the message: reply
send sms with the message: message
send sms with the message: that
send sms with the message: contains
send sms with the message: so many
send sms with the message: words so
send sms with the message: I have to
send sms with the message: split it
send sms with the message: to some
send sms with the message: parts
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29295276

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档