Shell Program to Find the Position of Substring in Given String - GeeksforGeeks

29 Dec, 2021

A string is made of many substrings or can say that if we delete one or more characters from the beginning or end then the remaining string is called substring. This article is about to write a shell program that will tell the position (index) of the substring in a given string. Let’s take an example of this.
Example: 
Given ( String ): "geeks for geeks is the best platform for computer science geek"
Input ( Substring ): "computer"
Output ( Position ): 42 ( string index starting from 1 ) ( first index, from where substring start )
We will discuss here mainly two approaches in which the first one will be brute force approach and second will be using bash commands.
Approach 1:
To write the script code follow the below steps
Step 1: make two choices input the main string or continue with default.
Step 2: according to user choice of user get string and substring using the read command.
Step 3: Now, run a loop to get the all character of the given string and compare those to the first character of the substring. 
Step 4: Run again a loop to check from matching character to match all other characters to find substring.
Shell Script Code:
# script to get the substring position in given string

# let give a string 
str="geeks for geeks is the best platform for computer science geeks"

# now ask user to give the new string or use the given default string
echo "Hello there, do you wanna give new string or use default"
echo 
echo "Enter 1 for new string"
echo "Enter 0 for continue"

# now read the choice form user
read choice
echo

# make the condition to check the choice and perform action according to that
if [[ choice == 1 ]]
then 
    # now ask reader to give the main string
    echo "Please, Enter the main string"
    
    # now read the string 
    read str
    echo
fi

# print a message
echo "Let's continue to get the index of the substring....."
echo

# make a loop to get the substring values from the user 
while [[ 1 ]]
do 
    # print the statement
    echo "Enter a substring to get the position of that string OR Enter -1 to get exit"
    
    # now read the substr
    read substr
    
    # make a condition to check the value of substr
    if [[ $substr != -1 ]]
    then 
        # # 1st approach code to get the substring position from given string ( 1st approach )
        # # This approach is comparison on char by char 
        # ************************************************************************
        
        # length of the given string
        lenGS=${#str}
        #length of the substr
        lenSS=${#substr}
        
        # check the condition where string length is less than substring length
        if [[ $lenGS -lt $lenSS ]] 
        then 
            echo "Sorry, Your substring exceed main string, Please Enter another"
            continue
        fi
        
        # variable to store position 
        pos=-1
        # variable to check
        found=0
        
        # run three native loop ( brute force approach ) 
        for (( i=0;i<lenGS;++i ))
        do
        
            if [[ ${str:i:1} == ${substr:0:1} ]]
            then 
            
                # now loop to check that here substring or not
                kstr=$i
                ksubstr=$i

                while (( kstr<lenGS && ksubstr<lenSS ))
                do 
                    if [[ ${str:kstr:1} != ${substr:ksubstr:1} ]]
                    then
                        break
                    fi
                    kstr=`expr $kstr + 1`
                    ksubstr=`expr $ksubstr + 1`
                done
                
                # check if substring found
                if [[ ${ksubstr} == ${lenSS} ]]
                then
                    echo "Your substring $substr is found at the index ${i+1}"
                    found=1
                    break
                fi
            fi
        done
        
        # check the substring found or not
        if [[ $found == 0 ]]
        then 
            echo "Sorry, Your substring $substr is not found in main string"
        fi
        echo
        #**********************************************************************
        
    else
        echo "okay! Closed"
        break
    fi
done

# Geeks for Geeks
    
    
    
Execution of the Script: 
Command: bash script.sh
Hello there, do you wanna give new string or use default

Enter 1 for new string
Enter 0 for continue
0

Let's continue to get the index of the substring.....

Enter a substring to get the position of that string OR Enter -1 to get exit
geeks
Your substring geeks is found at the index 1

Enter a substring to get the position of that string OR Enter -1 to get exit
best
Your substring best is found at the index 1

Enter a substring to get the position of that string OR Enter -1 to get exit
web 
Sorry, Your substring web is not found in main string

Enter a substring to get the position of that string OR Enter -1 to get exit
-1
okay! Closed
Output Screenshot: 
Approach 2:
To write the script code follow the below steps
Step 1: make two choices input the main string or continue with default.
Step 2: according to user choice of user get string using the read command.
Step 3:  get the substring from the user using the read command.
Step 4: Now run a loop and get all substring of the main string of the length of the given substring using the substring function in scripting.
Step 5: check all substring one by one and stop when you find a substring equal to the given substring.
Shell Script Code:
# script to get the substring position in given string

# let give a string 
str="geeks for geeks is the best platform for computer science geeks"

# now ask user to give the new string or use the given default string
echo "Hello there, do you wanna give new string or use default"
echo 
echo "Enter 1 for new string"
echo "Enter 0 for continue"

# now read the choice form user
read choice
echo

# make the condition to check the choice and perform action according to that
if [[ choice == 1 ]]
then 
    # now ask reader to give the main string
    echo "Please, Enter the main string"
    
    # now read the string 
    read str
    echo
fi

# print a message
echo "Let's continue to get the index of the substring....."
echo

# make a loop to get the substring values from the user 
while [[ 1 ]]
do 
    # print the statement
    echo "Enter a substring to get the position of that string OR Enter -1 to get exit"
    
    # now read the substr
    read substr
    
    # make a condition to check the value of substr
    if [[ $substr != -1 ]]
    then 
        # # 2nd approach code to get the substring position from given string ( 2nd approach )
        # # This approach is comparison on string by string using bash string function 
        # ************************************************************************
        
        pos=-1
        
        # length of the given string
        lenGS=${#str}
        #length of the substr
        lenSS=${#substr}
        
        # check the condition where string length is less than substring length
        if [[ $lenGS -lt $lenSS ]] 
        then 
            echo "Sorry, Your substring exceed main string, Please Enter another"
            continue
        fi
        
        # get the limit of the loop
        limit=`expr $lenGS - $lenSS + 1`
        
        # variable to check
        found=0
        
        # run a loop to check the all substring 
        for (( i=0; i<limit; i++ ))
        do
            # create substring from main string of the same length
            substr1=${str:$i:$lenSS}
            
            # now check if these two string equal or not 
            if [[ $substr == $substr1 ]]
            then 
                echo "So $substr substring position in main string is : `expr $i + 1`"
                found=1
                break;
            fi
        done
        
        # check the substring found or not
        if [[ $found == 0 ]]
        then 
            echo "Sorry, Your substring $substr is not found in main string"
        fi
        echo
        #**********************************************************************
        
    else
        echo "okay! Closed"
        break
    fi
done
Execution of the Script:
Command: bash script.sh
Hello there, do you wanna give new string or use default

Enter 1 for new string
Enter 0 for continue
0

Let's continue to get the index of the substring.....

Enter a substring to get the position of that string OR Enter -1 to get exit
computer
So computer substring position in main string is : 42

Enter a substring to get the position of that string OR Enter -1 to get exit
best
So best substring position in main string is : 24

Enter a substring to get the position of that string OR Enter -1 to get exit
geeksgeeks
Sorry, Your substring geeksgeeks is not found in main string

Enter a substring to get the position of that string OR Enter -1 to get exit
-1
okay! Closed
Output Screenshot: 
kapoorsagar226
subhra_jy
sagartomar9927
anikakapoor

Picked


Shell Script


Linux-Unix

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Thread functions in C/C++
nohup Command in Linux with Examples
mv command in Linux with examples
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples