需求:查找字符串中某个字符最后出现的位置(字符串查找)
1、rindex.sh代码:
复制代码 代码示例:
#!/bin/bash
strToCheck=$1;
charToSearch=$2;
let pos=`echo "$strToCheck" |
linuxjishu/13830.html target=_blank class=infotextkey>awk -F ''$charToSearch'' '{printf "%d", length($0)-length($NF)}'`
echo "char $charToSearch lastpos is: $pos"
调用:
复制代码 代码示例:
[zeal]$ sh rindex.sh www.jb200.com .
char . lastpos is: 10
Calfen则提供了一种比较自力更生的方式:自己用c写了个小程序来实现rindex的功能,gcc rindex.c -o rindex 之后shell就拥有可以调用的rindex了 :)
2、rindex.c代码:
复制代码 代码示例:
#
include <strings.h>
int main(int argc, char *argv[]){
char* wholeWord;
char subChar;
char* subWord;
int ret;
if(argc!=3){
printf("Use:rindex word charn");
exit(0);
}
wholeWord=argv[1];
subChar=*argv[2];
subWord=rindex(wholeWord,subChar);
if(0 == subWord)
ret = 0;
else
ret = (subWord-wholeWord+1);
printf("%dn",ret);
}