SoFunction
Updated on 2025-03-09

Shell scripts implement to find the last location of a character in a string

You need to find the last location of a character in the string. This function is available in PHP (strrpos) or Perl (rindex). You can't think of any of them in the shell for a moment. No one answered the post on the forum (I don’t know if the question is too simple or it is really profound...).

Because things were urgent and could not wait, I asked for help from my college classmates. Pacman is worthy of being a master, and he wakes up the dreamer in just a few seconds:

Code:

Copy the codeThe code is as follows:

#!/bin/bash

strToCheck=$1;
charToSearch=$2;

let pos=`echo "$strToCheck" | awk -F ''$charToSearch'' '{printf "%d", length($0)-length($NF)}'`

echo "char $charToSearch lastpos is: $pos"


Example of usage:
Copy the codeThe code is as follows:

[zeal]$ sh .
char . lastpos is: 10

Calfen provides a more self-reliant way: write a small program in c to implement the function of rindex, and then gcc -o rindex shell has a rindex that can be called :)
Code:

Copy the codeThe code is as follows:

#include <>
int main(int argc, char *argv[]){
    char* wholeWord;
    char subChar;
    char* subWord;

    int ret;

    if(argc!=3){
        printf("Use:rindex word char\n");
        exit(0);
    }
    wholeWord=argv[1];
    subChar=*argv[2];
    subWord=rindex(wholeWord,subChar);

    if(0 == subWord)
        ret = 0;
    else
        ret = (subWord-wholeWord+1);
    printf("%d\n",ret);
}