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
4 min read
How to check if a String Contains a Substring in PHP ? Checking whether a string contains a specific substring is a common task in PHP. Whether you're parsing user input, filtering content, or building search functionality, substring checking plays a crucial role.MethodsBelow are the following methods by which we can check if a string contains a substri
1 min read
How to Substring a String in Python A String is a collection of characters arranged in a particular order. A portion of a string is known as a substring. For instance, suppose we have the string "GeeksForGeeks". In that case, some of its substrings are "Geeks", "For", "eeks", and so on. This article will discuss how to substring a str
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
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
How to Find Length of String in Bash Script? In this article, we are going to see how to get string length in Bash scripting. Here are a few ways from which we can get the length of the string in BASH: Using the # operatorUsing while loopUsing expr commandUsing awk commandUsing wc command Using these mentioned tools and commands, we will be ab
5 min read
How to get the last character of a string in PHP ? In this article, we will find the last character of a string in PHP. The last character can be found using the following methods.Using array() Method: In this method, we will find the length of the string, then print the value of (length-1). For example, if the string is "Akshit" Its length is 6, in
2 min read
CSES Solutions - Substring Order II You are given a string of length n. If all of its substrings (not necessarily distinct) are ordered lexicographically, what is the kth smallest of them? Examples: Input: String = "agctagctagct" , k = 7Output: AGCExplanation: The 7 smallest substrings in order are a, a, a, ag, ag, ag and agc. Input:
15+ min read