check if string contains substring

How to Check if String Contains Substring in Bash

Sometimes you may need to find out if a string contains another substring in bash. There are several ways to do this in Linux. Here is how to check if string contains substring in bash.


How to Check if String Contains Substring in Bash

There are several ways to check if string contains substring in bash.


1. Using Wildcards

You can easily use wildcard characters around substring and use it in an if statement, to compare with original string, to check if substring is present or not.

Here is a simple script /home/substring.sh that uses if statement and == operator to check if substring is found within string.

#!/bin/bash

STR='test string'
SUB='test'
if [[ "$STR" == *"$SUB"* ]]; then
  echo "substring present"
fi

When you run the script, you will get following output

$ /home/substring.sh
substring present


2. Using CASE statement

You may also use CASE statement instead of using if statement as shown below. Again we use the same idea of adding * wildcard characters around substring and comparing with original string.

#!/bin/bash

STR='test string'
SUB='test'

case $STR in

  *"$SUB"*)
    echo -n "substring present"
    ;;
esac


3. Using GREP

You may also use GREP command to find is a substring is present in a string or not. This is a simple grep command where we search for substring in original string. We also use -q option to perform silent search and omit the output.

#!/bin/bash

STR='test string'
SUB='test'

if grep -q "$SUB" <<< "$STR"; then
  echo "substring present"
fi

That’s it. In this article, we have looked at how to see if a substring is present in another string, in different ways. You may also use other tools like awk and sed to perform that same operation.

Also read:

Shell Script to Remove Last N Characters from String
How to Find Unused IP Address in Network
How to Setup Email Alerts for Root Login
How to Extract IP Address from Server Log File
How to Switch User Without Password in Ubuntu

Leave a Reply

Your email address will not be published. Required fields are marked *