bash根据字符长度将变量拆分为两个或更多

时间:2015-02-15 09:40:37

标签: bash

我为SMS自动回复器构建了一个脚本,我的目标是当一个短信内容的字符长度超过160时,它会将内容分成两个或多个变量,然后单独发送。

myvar="this variable has more than ten character length"

该变量有48个字符长度,如何从长度1到长度25和长度26到48打印该变量?所以我最后会有2个变量并用sms发送这些变量:

firstvar="this variable has more th"
secondvar="an ten character length"

我知道有一个命令split但是我的openwrt不支持该命令,所以我必须找到另一种方法来做到这一点。

3 个答案:

答案 0 :(得分:0)

Bash可以使用它的替换规则将变量拆分为子串。

echo ${variable:4:8}

将显示从偏移量4开始的八个字符。偏移从零开始。

一般情况下:     $ {参数:偏移量:长度}

答案 1 :(得分:0)

此代码段可以帮助您:

myvar="this variable has more than ten character length"
size=${#myvar} 
if [ $size -gt 25 ]; then
    firstvar=${myvar:0:25}
    secondvar=${myvar:26:size}
    echo "$firstvar"
    echo "$secondvar"
fi

答案 2 :(得分:0)

纯粹的Bash可能性,没有外部工具(因此仅依赖于Bash而没有其他特定的第三方工具)且没有子shell:

#!/bin/bash

mysms="this variable has more than ten character length"
maxlength=25

sms_tmp=$mysms
sms_ary=()
while [[ $sms_tmp ]]; do
    sms_ary+=( "${sms_tmp::maxlength}" )
    sms_tmp=${sms_tmp:maxlength}
done

# At this point, you have your sms split in the array sms_ary:

# You can print them, one per line:
printf '%s\n' "${sms_ary[@]}"

# You can print them, one per line, with header:
printf -- '--START SMS-- %s --END SMS--\n' "${sms_ary[@]}"

# You can print them, space padded (spaces on the right):
printf -- "--START SMS-- %-$(maxlength}s --END SMS--\n" "${sms_ary[@]}"

# You can print them, space padded (spaces on the left):
printf -- "--START SMS-- %${maxlength}s --END SMS--\n" "${sms_ary[@]}"

# You can loop through them:
for sms in "${sms_ary[@]}"; do
    printf 'Doing stuff with SMS: %s\n' "$sms"
done

# You can loop through them with index (C-style loop):
for ((i=0;i<${#sms_ary[@]};++i)); do
    printf 'This is SMS #%d at index %d: %s\n' "$((i+1))" "$i" "${sms_ary[i]}"
done

# You can loop through them (using array key as variable):
n=1
for i in "${!sms_ary[@]}"; do
    printf 'This is SMS #%d at index %d: %s\n' "$((n++))" "$i" "${sms_ary[i]}"
done

# Here's the number of SMS:
printf 'That was fun. There were %d chunks of SMS\n' "${#sms_ary[@]}"

分割字符串的另一种方法:

#!/bin/bash

mysms="this variable has more than ten character length"
maxlength=25

sms_ary=()
for ((i=0;i<${#mysms};i+=maxlength)); do
    sms_ary+=( "${mysms:i:maxlength}" )
done

# Same as before, at this point you have your chunks in array sms_ary