开发者

How do I perform a simple regular expression match in bash?

I'm trying to match the number that's in the beginning of a string

452MATCHME

With this 开发者_运维问答simple regex

/^\d*/

And I want this result, saved in a variable

452

But I can't find a way to get the result of the operation. I've read this tutorial, but it describes an array BASH_REMATCH where all match results of =~ operations are stored. That array doesn't exist in my case though, for some reason. I'm using bash version 4.2.10(1).

The only other option I can think of is grep, but that can only output which lines matched the regex, as far as I know.

How can I achieve my result?


var=452MATCHME
echo ${var%%[^0-9]*}

This will delete from the first non-digit to the end.

Bash parameter is sufficient for most cases so I'd suggest you get familiar with it. Here is the link for bash pattern: http://www.gnu.org/software/bash/manual/bashref.html#Pattern-Matching


this will work:

if [[ "452MATCHME" =~ ^([0-9]+).* ]]
then 
    echo ${BASH_REMATCH[1]};
fi

P.S: I'm using bash 3.0 version, it's just you regex that isn't well formed.


So it seems the issue was that BASH regex doesn't support \d. Use [0-9] instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜