Testing regular expressions in a Bash script

Andrea Telatin
#!/ngs/sh
Published in
1 min readMar 2, 2018

I noticed that several shell script would be simpler and more powerful if they adopted some pattern matching, but this technique so widely adopted in most scripting languages (like Python, PHP and — of course — Perl) is less used in Bash scripts.

Let’s start immediately with an example:

if [[ $FILENAME =~ txt$ ]]
then
echo "This seems to be the a text file, right?"
fi

The regular expression here is txt$, where the trailing dollar requires the pattern “txt” to be at the end of the string contained in the $FILENAME variable.

The pattern matching operator is =~, like in Perl, and the regular expression syntax is very similar to grep patterns. Some examples:

  • The dot is the wildcard.
  • You can match ranges. [0–9] will match any single digit. [A-Z] any uppercase letter.
  • ^, at the beginning, will force the pattern to be found at the beginning of the string, like $ at the end.

--

--