Index of Substring in String

To find the index of substring in a string in Bash, there are many classical ways.

But, in this tutorial, we will get the prefix string present before the substring in the given string, and the length of this prefix string should be the index of substring in the string.

Also, we need to make a check if the substring is not present in the string. If substring is not present, then we get a prefix same as the string. We may use this as a check to check if the substring is present in the string or not.

Example

In the following script, we take two strings: str and substr. We shall find the index of substr in the string str.

Example.sh

str="hello world"
substr="world"

prefix=${str%%$substr*}
index=${#prefix}

if [[ index -eq ${#str} ]];
then
    echo "Substring is not present in string."
else
    echo "Index of substring in string : $index"
fi

Output

Index of substring in string : 6
ADVERTISEMENT

Conclusion

In this Bash Tutorial, we have learnt how to find the index of a substring in a string in Bash shell.