Bash - Regex

About

Bash Binary operator

When the additional regexp binary operator =~ is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)).

The operator has the same precedence as == and !=

The return value is:

  • 0 if the string matches the pattern
  • 2 If the regular expression is syntactically incorrect
  • 1 otherwise.

Others:

  • If the shell option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters.
  • Any part of the pattern may be quoted to force it to be matched as a string.
  • Capturing group are saved in the BASH_REMATCH variable.

Example:

  • First
f="helloNico.jpg"
regex=$'[0-9]+_([a-z]+)_[0-9a-z]*'

if [[ $f =~ $regex ]]
then
	name="${BASH_REMATCH[1]}"
	echo "${name}.jpg"    # concatenate strings
	name="${name}.jpg"    # same thing stored in a variable
else
	echo "$f doesn't match" >&2 # this could get noisy if there are a lot of non-matching files
fi

Documentation / Reference


Powered by ComboStrap