UNIX中给定字符串中第n次出现字符的索引

时间:2013-10-23 17:07:13

标签: shell unix ksh

考虑字符串

s=pqrPQR456PQRpqr

现在

expr index $s p

给我ans为1

但是如何找到任意重复字符的R或索引之后的p的索引;这就是我无法得到的。

3 个答案:

答案 0 :(得分:1)

您可以根据索引获得子字符串。

$ s=pqrPQR456PQRpqr
$ n=$(expr index $s p)
$ echo "${s:$n}"
qrPQR456PQRpqr

这至少为您提供了您正在搜索的字符后面的字符串。

答案 1 :(得分:0)


#!/bin/ksh
ind=`expr index string substring`
count_occ=`echo "$string"|tr -cd $substring|wc -c`
count=1
echo " The $substring occurs at : $ind "
while [ $count -lt $count_ind ]
do
     rem_str=${string:$ind}
     new_ind=`expr index $rem_str $substring`
     count=`expr $count + 1`
     ind=`expr $ind + $new_ind`
     echo "$ind"
done

答案 2 :(得分:0)

这是一个函数,它可以在不调用expr等外部程序的情况下提供单个字符偏移量。它从零而不是一个计算位置(零更常用于第一个字符位置)。

# Take two parameters:
# $1 - the string
# $2 - target character
# $3 - the offset, default is 0
function strchr {
   typeset -i offset
   string="$1"
   target="$2"
   offset="$3"
   (( $# < 3 )) && offset=0

   while (( $offset < ${#string} ))
   do
       char=${string:$offset:1}
       [[ $char == $target ]] && break;
       (( offset++ ))
   done
   echo "$offset"
}

s='pqrPQR456PQRpqr'
i=$(strchr "$s" 'p')
echo "i: $i"
j=$(strchr "$s" 'p' $(( $i + 1 )) )
echo "j: $j"

给出:

i: 0
j: 12