Bash – Find index of last occurrence of substring in string

To find index of last occurrence of substring in a string in Bash scripting, you can reverse the string and substring, find the index of reversed substring in the reversed string and, then adjust the index for last occurrence of substring in string.

Example

In the following script, we take a string in str and substring in substr. We find the index of last occurrence of substring in the string, and print the index to output using echo.

example.sh

</>
Copy
#!/bin/bash

str="hello world as world sd"
substr="world"

#reverse strings
reverse_str=$(echo $str | rev)
reverse_substr=$(echo $substr | rev)

#find index of reversed substring in reversed string
prefix=${reverse_str%%$reverse_substr*}
reverse_index=${#prefix}

#calculate last index
index=$(( ${#str} - ${#substr} - $reverse_index ))

if [[ index -lt 0 ]];
then
    echo "Substring is not present in string."
else
    echo "Index of last occurrence of substring in string : $index"
fi

Bash Version: GNU bash, version 5.2.15(1)-release (aarch64-apple-darwin22.1.0)

Output

sh-3.2# bash example.sh 
Index of last occurrence of substring in string : 15

References

Bash – Reverse a string

Bash – Index of substring in string

Bash – String length

Bash If-else

Conclusion

In this Bash Tutorial, we learned how to find the index of last occurrence of specific substring in given string.