1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
#!/bin/sh index_char() { # 参数需>=两个 if [ $# -lt 2 ]; then echo 'Lack of Parameters' return fi # n: 待索引第n个字符 declare -i n if [ $# -eq 2 ]; then n=1 elif [ $# -eq 3 ]; then n=$3 fi string=$1 target=$2 declare -i target_len=`expr length $target` if [ $target_len -gt 1 ]; then echo 'Not support to index string' return fi declare -i left=0 declare -i index=0 declare -i len=${#string} declare -i result=0 for i in `seq $n`; do index=`expr index $string $target` left=$len-$index string=${string:$index:${left}} result=$result+$index if [ $index -eq 0 ]; then echo 'Out Of Range' break; fi done echo $result } index_char $@ |
Continue reading...