Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

How to match digits in regex in bash script

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...