#!/bin/bash
message="This message is so freaking long that I have to split it into two or more messages"
split=${#message}
array=( ${message:0:5} ${message:5:5} ${message:10:5} ${message:15:5} ${message:20:5})
for i in "${array[@]}"
do
echo "send me a message with \"$i\""
done
输出如下:
send me a message with "This"
send me a message with "messa"
send me a message with "ge"
send me a message with "is"
send me a message with "so"
send me a message with "f"
send me a message with "reaki"
但我不想那样,我想这样:
send me a message with "This "
send me a message with "messa"
send me a message with "ge is"
send me a message with "so fr"
send me a message with "eakin"
send me a message with "g lon"
send me a message with "g tha"
我该如何解决?我用google搜索但我仍然无法按照我想要的方式工作,我不知道for loop
是不正确还是${message:x:x}
。
答案 0 :(得分:2)
请使用更多报价!</ p>
$ array=( "${message:0:5}" "${message:5:5}" "${message:10 :5}" "${message:15:5}" "${message:20:5}" )
$ for i in "${array[@]}"
> do
> echo "send me a message with \"$i\""
> done
send me a message with "This "
send me a message with "messa"
send me a message with "ge is"
send me a message with " so f"
send me a message with "reaki"
单词中的空格导致它们被视为数组中的单独元素,这导致了您观察到的行为。用双引号括起每个元素可以防止这个单词分裂。