bash - How to match digits in regex -
i'm trying match lines against regex contains digits.
bash version 3.2.25:
#!/bin/bash s="aaa (bbb 123) ccc" regex="aaa \(bbb \d+\) ccc" if [[ $s =~ $regex ]]; echo $s matches $regex else echo $s doesnt match $regex fi result:
aaa (bbb 123) ccc doesnt match aaa \(bbb \d+\) ccc if put regex="aaa \(bbb .+\) ccc" works doesn't meet requirement match digits only.
why doesn't \d+ match 123?
either use standard character set or posix-compliant notation:
[0-9] [[:digit:]] as read in finding numbers @ beginning of filename regex:
\d,\wdon't work in posix regular expressions, use[:digit:]though
so expression should 1 of these:
regex="aaa \(bbb [0-9]+\) ccc" # ^^^^^^ regex="aaa \(bbb [[:digit:]]+\) ccc" # ^^^^^^^^^^^^ all together, script can this:
#!/bin/bash s="aaa (bbb 123) ccc" regex="aaa \(bbb [[:digit:]]+\) ccc" if [[ $s =~ $regex ]]; 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
Comments
Post a Comment