出于某种原因,我无法使用bash构建我的脚本,唯一的方法是使用ash,我有这个短信自动响应脚本,每个回复必须最多160个字符长,它看起来像这样:
#!/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
Run Code Online (Sandbox Code Playgroud)
但它最终会像这样:
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
Run Code Online (Sandbox Code Playgroud)
我想要的是这样的:
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
Run Code Online (Sandbox Code Playgroud)
因此它按字符数分割而不是按字词分割,我该怎么做?
您的数组实际上不是数组,但请阅读http://mywiki.wooledge.org/WordSplitting以获取更多信息.
ash本机不支持数组,但您可以通过使用set:
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
Run Code Online (Sandbox Code Playgroud)
-
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
Run Code Online (Sandbox Code Playgroud)
有许多替代解决方案,这里有一个fold用于为您执行拆分工作,其附加优势是它可以在空格上打破以使消息更具可读性(man fold有关详细信息,请参阅参考资料):
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
Run Code Online (Sandbox Code Playgroud)
-
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
Run Code Online (Sandbox Code Playgroud)