Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash regex with quotes?

Tags:

regex

bash

quotes

The following code

number=1 if [[ $number =~ [0-9] ]] then   echo matched fi 

works. If I try to use quotes in the regex, however, it stops:

number=1 if [[ $number =~ "[0-9]" ]] then   echo matched fi 

I tried "\[0-9\]", too. What am I missing?

Funnily enough, bash advanced scripting guide suggests this should work.

Bash version 3.2.39.

like image 814
tpk Avatar asked Oct 20 '08 11:10

tpk


1 Answers

It was changed between 3.1 and 3.2. Guess the advanced guide needs an update.

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1. As always, the manual page (doc/bash.1) is the place to look for complete descriptions.

  1. New Features in Bash

snip

f. Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

Sadly this'll break existing quote using scripts unless you had the insight to store patterns in variables and use them instead of the regexes directly. Example below.

$ bash --version GNU bash, version 3.2.39(1)-release (i486-pc-linux-gnu) Copyright (C) 2007 Free Software Foundation, Inc. $ number=2 $ if [[ $number =~ "[0-9]" ]]; then echo match; fi $ if [[ $number =~ [0-9] ]]; then echo match; fi match $ re="[0-9]" $ if [[ $number =~ $re ]]; then echo MATCH; fi MATCH  $ bash --version GNU bash, version 3.00.0(1)-release (i586-suse-linux) Copyright (C) 2004 Free Software Foundation, Inc. $ number=2 $ if [[ $number =~ "[0-9]" ]]; then echo match; fi match $ if [[ "$number" =~ [0-9] ]]; then echo match; fi match 
like image 139
Vinko Vrsalovic Avatar answered Oct 05 '22 02:10

Vinko Vrsalovic