80

I'm trying to match some lines against regex that contains digits.

Bash version 3.2.25:

#!/bin/bash

s="AAA (bbb 123) CCC"
regex="AAA \(bbb \d+\) CCC"
if [[ $s =~ $regex ]]; then
  echo $s matches $regex
else
  echo $s doesnt match $regex
fi

Result:

AAA (bbb 123) CCC doesnt match AAA \(bbb \d+\) CCC

If I put regex="AAA \(bbb .+\) CCC" it works but it doesn't meet my requirement to match digits only.

Why doesn't \d+ match 123?

1
  • \d is not valid in an extended regex. Commented Oct 2, 2023 at 11:47

2 Answers 2

132

Either use standard character set or POSIX-compliant notation:

[0-9]    
[[:digit:]]    

As read in Finding only numbers at the beginning of a filename with regex:

\d and \w don't work in POSIX regular expressions, you could use [:digit:] though

so your expression should be one of these:

regex="AAA \(bbb [0-9]+\) CCC"
#                ^^^^^^
regex="AAA \(bbb [[:digit:]]+\) CCC"
#                ^^^^^^^^^^^^

All together, your script can be like this:

#!/bin/bash

s="AAA (bbb 123) CCC"
regex="AAA \(bbb [[:digit:]]+\) CCC"
if [[ $s =~ $regex ]]; then
  echo "$s matches $regex"
else
  echo "$s doesn't match $regex"
fi

Let's run it:

$ ./digits.sh
AAA (bbb 123) CCC matches AAA \(bbb [[:digit:]]+\) CCC
Sign up to request clarification or add additional context in comments.

1 Comment

Why doesn't it work if $regex is replaced by the string containing its content? I.e. if [[ $s =~ "AAA \(bbb [[:digit:]]+\) CCC" ]]; then.
20

Digit notation \d doesn't work with your bash version. Use [0-9] instead:

regex="AAA \(bbb [0-9]+\) CCC"

5 Comments

At least with bash 4.3.11 (the one that comes with Ubuntu 14.04) [0-9]+ doesn't work either, but [0-9]* does. Maybe + is unsupported?
[0-9]+ worked for me on older BASH 3.2 as well so not sure why Ubuntu BASH is not liking it.
Hmmm, never mind, I got confused: it's grep that doesn't handle + (at least not without additional options). I got confused because my script both uses bash regex matching and grep.
oh grep by default uses BRE so + needs to be escaped. Otherwise you can use grep -E to support extended regex like above.
Should [0-9]{1,3} for 1 to three digit numbers work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.