5 Quick Bash Techniques to Test If a String Contains a Substring
This article demonstrates five Bash methods—using grep, the =~ operator, wildcards, case statements, and parameter substitution—to determine whether one string contains another, and also shows two ways to check if a file includes a specific text.
When writing Bash scripts, you often need to verify whether a string contains a given substring. Below are several common techniques.
1. Using grep
str1="abcdefgh"
str2="def"
result=$(echo $str1 | grep "${str2}")
if [[ "$result" != "" ]]
then
echo "包含"
else
echo "不包含"
fiThis method pipes the long string to grep and checks if the result is non‑empty.
2. String operator =~
str1="abcdefgh"
str2="def"
if [[ $str1 =~ $str2 ]]
then
echo "包含"
else
echo "不包含"
fiThe =~ operator directly tests for a match.
3. Using wildcards
str1="abcdefgh"
str2="def"
if [[ $str1 == *$str2* ]]
then
echo "包含"
else
echo "不包含"
fiThe asterisk (*) acts as a wildcard for any characters surrounding the substring.
4. Using a case statement
str1="abcdefgh"
str2="def"
case $str1 in
*"$str2"*) echo Enemy Spot ;;
*) echo nope ;;
esacThe pattern *"$str2"* matches when the substring is present.
5. Using parameter replacement
str1="abcdefgh"
str2="def"
if [[ ${str1/${str2}//} == $str1 ]]
then
echo "不包含"
else
echo "包含"
fiThis technique removes the substring from the original string and compares the result.
Checking if a file contains a given string
Method 1: grep -c
# grep -c returns the number of matching lines
FIND_FILE="/home/linduo/test/Test.txt"
FIND_STR="Hello Weijishu"
if [ `grep -c "$FIND_STR" $FIND_FILE` -ne '0' ]; then
echo "The File Has Hello Weijishu!"
exit 0
fiMethod 2: cat with while read
FIND_FILE="/home/weijishu/test/Test.txt"
FIND_STR="Hello Weijishu"
cat $FIND_FILE | while read line
do
if [[ $line =~ $FIND_STR ]]; then
echo "The File Has Hello Weijishu!"
fi
doneNote the difference between using [[ ... ]] and [ ... ] in conditional expressions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
