This week I needed to write a couple of scripts to pattern match some strings in a text file. My typical go to for these types of problems is python, but I wanted to learn something new so I started poking around bash(1) to see if there was a way to do this in a shell script. After a bit of reading, I came across the =~ operator which provides a way to pattern match in the shell:
An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordâ ingly (as in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise.
To test this I created the following bash function:
findMatch() {
if [[ "${1}" =~ "is a" ]]; then
echo "The string \"is a\" was found in string ${1}"
else
echo "The string \"is a\" was not not found in string ${1}"
fi
}
Running findMatch with the argument “This is a string” turned up a match:
The string "is a" was found in string This is a string
Pattern matching is case sensitive by default so it won’t match the string “This Is A string”:
The string "is a" was not not found in string This Is A string
If you need your matches to be be case insensitive you can set nocasematch with shopt:
shopt -s nocasematch
If we call findMatch with the same option as above we will now get a match:
The string "is a" was found in string This Is A string
This is a super useful feature to add to the shell scripting utility belt!