In this tutorial, the Bash script is designed to determine whether a string contains a specific substring.
There are multiple ways to perform this check, each outlined below for clarity.
Using the Comparison Operator to Check for Substring exists or not
- Define a string variable containing the text.
- Use if statements to compare the string with the desired substring using the equality operator (
==
) and a wildcard(*
). - Finally, print the string if the substring is found.
mainstring='Welcome to w3schools'
if [[ $mainstring == *"w3schools"* ]]; then
echo "w3schools exists in the main string"
fi
Use Regular Expressions to Find a Substring
The =~
operator facilitates substring search within a given string, used within an if block.
Example code:
mainstring='Welcome to w3schools'
if [[ $mainstring =~ "w3schools" ]]; then
echo "w3schools exists in the main string"
fi
Use the grep command
The grep command is employed to search for a specified string, piped to the main string for comparison.
mainstring='Welcome to w3schools'
if echo "$mainstring" | grep -q "w3schools"; then
echo "w3schools exists in the main string"
fi
These methods offer different approaches to checking if a string contains a particular substring, providing flexibility for different use cases.