Bash Substring Verification

Bash provides various mechanisms for working with substrings. Here are some common ways to verify if a substring exists within a string:

  1. Using grep command:
    if echo "$string" | grep -q "$substring"; then
    echo "Substring found"
    else
    echo "Substring not found"
    fi
  2. Using Bash’s built-in pattern matching:
    if [[ $string == *"$substring"* ]]; then
    echo "Substring found"
    else
    echo "Substring not found"
    fi
  3. Using parameter expansion:
    if [[ "${string/$substring}" != "$string" ]]; then
    echo "Substring found"
    else
    echo "Substring not found"
    fi

In all of these examples, replace $string and $substring with the actual string and substring you want to work with.

Leave a Comment