[GRLUG] Bash regex

Robert Citek robert.citek at gmail.com
Tue May 7 14:27:47 EDT 2013


On Tue, May 7, 2013 at 2:21 PM, L. V. Lammert <lvl at omnitec.net> wrote:
> I had tried single, double, as well as no quotes, .. none would match the
> YYYY-MM string when properly formatted.
>
> I ended up with:
>
> if [[ ! $1 =~ [0-9][0-9][0-9][0-9]-[0-9][0-9] ]] ; then
>    echo '    Usage: backup YYYY-MM'
>    exit
> fi
>
> I believe the main problem was the missing 'number' modifier usable in
> bash, so I had to explictly repeat the digits.

Can you show what you used as a test?

Regex in single quotes:

$ [[ "2013-06" =~ '[0-9]{4}-[0-9]{2}' ]] && echo yes || echo no
no

Regex in double quotes:

# [[ "2013-06" =~ "[0-9]{4}-[0-9]{2}" ]] && echo yes || echo no
no

Regex without quotes:

$ [[ "2013-06" =~ [0-9]{4}-[0-9]{2} ]] && echo yes || echo no
yes

Regex as variable:

$ regex="[0-9]{4}-[0-9]{2}"
$ [[ "2013-06" =~ ${regex} ]] && echo yes || echo no
yes

Regards,
- Robert


More information about the grlug mailing list