0

I'm sure this is a small thing, but I'm relatively new to bash and regular expressions,

given a string summary = 689 in 2s = 350.3/s Avg: 4 Min: 0 Max: 84 Err: 24 (3.48%) I want to check if the text Err: [1-9] occurs in the given string in a bash script. In order to achieve that I have written the following script

digit="Err: 8"

if [[ $digit =~ 'Err: [1-9]' ]]; 
then
    echo "$digit is a digit"
else
    echo "oops"
fi

However this does not work, it will goes into the false. When I tested the regular expression with an online tool it seem to work fine, I'm not sure whats wrong here.

tmp dev
  • 8,043
  • 16
  • 53
  • 108
  • Put your regex pattern in a variable and then use that variable in if statament. – Alireza Aug 31 '21 at 22:16
  • 1
    The `[1-9]` part is in quotes, so it's treated as a literal string rather than a pattern. You can use use `'Err: '[1-9]` or `Err:\ [1-9]` or put the pattern in a variable as Alireza said (and then don't put quotes around the variable when you use it). See: [How do I use regular expressions in bash scripts?](https://stackoverflow.com/questions/304864/how-do-i-use-regular-expressions-in-bash-scripts) BTW, you don't really need full regex here, you could just use a glob (aka wildcard) pattern: `if [[ "$digit" = *'Err: '[1-9]* ]]` – Gordon Davisson Aug 31 '21 at 22:29

2 Answers2

1

You can put your regex pattern in a variable and use that variable in if statement like this:

digit="Err: 8"
pattern="Err: [1-9]"
if [[ $digit =~ $pattern ]]; 
then
    echo "$digit is a digit"
else
    echo "oops"
fi

or if you don't want to use an additional variable you can change your if statement like this:

digit="Err: 8"
if [[ $digit =~ Err:\ [1-9] ]]; 
then
    echo "$digit is a digit"
else
    echo "oops"
fi
Alireza
  • 2,103
  • 1
  • 6
  • 19
1

You could use [[:blank:]] to match spaces and tabs without the surrounding quotes:

if [[ $digit =~ Err:[[:blank:]][1-9] ]]; 

Or you can escape the space:

if [[ $digit =~ Err:\ [1-9] ]];

Or put the pattern with quotes in a variable:

pattern='Err: [1-9]'
if [[ $digit =~ $pattern ]];

As the first example string seems to have multiple spaces, you could repeat the character class:

digit="summary =    689 in     2s =  350.3/s Avg:     4 Min:     0 Max:    84 Err:    24 (3.48%)"
pattern='Err: [1-9]'
if [[ $digit =~ Err:[[:blank:]]+[1-9] ]];
then
    echo "$digit is a digit"
else
    echo "oops"
fi

Output

summary =    689 in     2s =  350.3/s Avg:     4 Min:     0 Max:    84 Err:    24 (3.48%) is a digit
The fourth bird
  • 154,723
  • 16
  • 55
  • 70