2015-03-27 8 views
5

Per qualche motivo, non posso usare bash per creare il mio script, l'unico modo per farlo è con ash, ho questo script di risponditore automatico di sms, ogni risposta deve essere al massimo 160 chacters lungo, assomiglia a questo:Come utilizzare la matrice nella cenere?

#!/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 

ma finisce così:

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 

Quello che voglio è qualcosa di simile:

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 

Quindi si divide per il numero di caratteri invece di dividere per parole, come posso farlo?

risposta

5

L'array non è in realtà un array, ma leggi http://mywiki.wooledge.org/WordSplitting per maggiori informazioni.

ash non supporta nativamente gli array, ma si può eludere che utilizzando 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 

-

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 

Ci sono molte soluzioni alternative a questo, ecco uno di loro utilizzando fold a fai il lavoro di suddivisione per te con l'ulteriore vantaggio che può rompere gli spazi per rendere i messaggi un po 'più leggibili (vedi man fold per maggiori informazioni):

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 

-

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 
+1

Grazie compagno, questo davvero mi aiuta: D – Lin

Problemi correlati