Shell Program to Find the Position of Substring in Given String
Last Updated :
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:


Similar Reads
Find the Longest Non-Prefix-Suffix Substring in the Given String
Given a string s of length n. The task is to determine the longest substring t such that t is neither the prefix nor the suffix of string s, and that substring must appear as both prefix and suffix of the string s. If no such string exists, print -1. Example: Input: s = "fixprefixsuffix"Output: fix
7 min read
How to get a substring between two strings in PHP?
To get a substring between two strings there are few popular ways to do so. Below the procedures are explained with the example.Examples: Input:$string="hey, How are you?"If we need to extract the substring between "How" and "you" then the output should be are Output:"Are"Input:Hey, Welcome to Geeks
5 min read
How to check if a String Contains a Substring in PHP ?
A string is a collection of given characters and a substring is a string present in a given string. In this article, we are going to check if the given string contains a substring by using the PHP strpos() function. Syntax: strpos($original_string,$sub_string);Parameters: original_string : The input
3 min read
Find line number of a specific string or substring or word from a .txt file in Python
Finding the line number of a specific string and its substring is a common operation performed by text editors or any application with some level of text processing capabilities. In this article, you will learn how to find line number of a specific string or substring or word from a .txt (plain tex
4 min read
How to get the position of character in a string in PHP ?
In this article, we will get the position of the character in the given string in PHP. String is a set of characters. We will get the position of the character in a string by using strpos() function. Syntax: strpos(string, character, start_pos) Parameters: string (mandatory): This parameter refers t
2 min read
Print Lines Starting with String in Linux
Printing lines that contain a particular string at the beginning is quite annoying to manually deal with, so we can make use of bash to design a shell script. The most versatile and powerful tool for searching patterns or lines is by using grep, awk, or sed to find the most efficient solution to the
5 min read
How to Check Whether a String Contains a Substring in JavaScript?
Given two strings, check if one string is substring of another. "bce" is substring of "abcde""ae" is not substring of "abcde"Empty String is a substring of all stringsUsing includes() - Most used and Simplest MethodThe includes() method checks whether a string contains a substring. [GFGTABS] JavaScr
2 min read
C# - Different Ways to Find All Substrings in a String
Given a string as an input we need to find all the substrings present in the given string. Example: Input: geeks Output: g e e k s ge ee ek ks gee eek eks geek eeks geeks Input: ab Output: a b abMethod 1: Using Substring() method We can find all the substrings from the given string using the Substri
3 min read
Minimize operations to make string Z equal to T by appending subsequence of S
Given two strings S and T, and an empty string Z, the task is to print the minimum operations required to make string Z equal to T by appending any subsequence of S at the end of Z. If it is impossible to do so, then print -1. Example: Input: S = "aabce", T="ace" Output: 1 Input: S = "abacaba", T =
10 min read
Insert string at specified position in PHP
Given a sentence, a string and the position, the task is to insert the given string at the specified position. We will start counting the position from zero. See the examples below. Input : sentence = 'I am happy today.' string = 'very' position = 4 Output :I am very happy today. Input : sentence =
3 min read