BASH Programming

How to Use Bash =~ Regex to Match Multiple Strings

One of the powerful features of Bash is its ability to use regular expressions to match patterns in strings and it becomes useful when dealing with text data in scripts and automating tasks. In this article, we will explore how to use the BASH =~ operator with regular expressions to match multiple strings.

What is =~ Regex in Bash

The bash =~ operator allows us to match a regular expression against a string and it returns true if the expression matches the entire string, in the other case it returns false.

Using Bash =~ Regex to Match Multiple Strings

In bash scripting, the “=” operator is used to match a regular expression against a string. With regex, you can match a single string or a pattern of strings. However, there are situations where you need to match multiple strings in a single operation so here is the syntax for matching multiple strings:

[[$<string-name>=~$<patterns>]]

To further illustrate I have given an example bash script that contains two strings and five matches that I want to make, below is the respective script:

#!/bin/bash
myString="Hello and welcome to LinuxHint.com"
mystring="greetings and welcome to Linux Mint"
patterns=("Hello" "welcome" "LinuxHint" "Mint" "APPLE")
matched1=0
matched2=0

for pattern in "${patterns[@]}"
do
  if [[ $myString =~ $pattern ]]; then
    echo "The string1 matches the pattern: $pattern"
    matched1=1
  fi

  if [[ $mystring =~ $pattern ]]; then
    echo "The string2 matches the pattern: $pattern"
    matched2=1
  fi
done

This code defines two strings myString and mystring, and an array pattern containing the patterns to match. It then loops through the patterns and checks if each one is found in myString and mystring using if statements with the =~ operator. If a match is found in a string, the code displays a message regarding pattern match whereas if no matches are found in a string, the code will print a message that will indicate that the string does not match any of the given patterns.

The matched = 1 statement inside the for loop is used to indicate that the current pattern being checked has been found in the input string.If the matched variable remains 0 after checking all patterns, it means none of the patterns were found in the input string and here is the output for the code:

Conclusion

Bash scripting comes with a variety of options to automate the tasks. The bash =~ operator with regular expressions is used to match multiple strings and this guide illustrates how to use this operator by the help of an example that matches a set of samples with two strings.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.