Bash脚本正则表达式 [英] Bash scripting regular expressions
问题描述
我正在尝试从4.6或2.8格式的字符串中匹配版本号.我要在我的.bashrc文件中的函数中最终使用以下内容来找到操作系统版本:
功能测试(){string ="abc ABC12 123 3.4 def";echo`expr match"$ string"'[0-9] [.] [0-9]'`}
但是,这与字符串中的3.4不匹配.有人可以在这里向我指出正确的方向吗?
谢谢.
首先,您可以删除 echo
- expr
在任何情况下都将其结果打印到stdout./p>
其次,您的正则表达式需要使用方括号(否则,它会打印匹配的字符数,而不是匹配项本身),并且需要以.*
开头.
expr匹配"$ string"'.* \([0-9] [.] [0-9] \)'
在 info expr
页面上:
STRING:正则表达式
执行模式匹配.参数被转换为字符串第二个被认为是(基本,la GNU`grep')正则表达式,其中暗含前缀"^".首先然后将参数与此正则表达式匹配.如果匹配成功并且REGEX使用`\('和`\)',则`:'表达式返回与STRING相匹配的STRING部分子表达否则,返回字符数匹配.
I'm trying to match a version number from a string in the format 4.6, or 2.8. I have the following which I will eventually use in a function in my .bashrc file to find the OS version:
function test () {
string="abc ABC12 123 3.4 def";
echo `expr match "$string" '[0-9][.][0-9]'`
}
However, this doesn't match the 3.4 in the string. Can anyone point me in the right direction here?
Thanks.
First, you can drop the echo
- expr
prints its result to stdout in any case.
Second, your regex needs brackets (otherwise it prints the number of characters matched, not the match itself), and it needs to begin with .*
.
expr match "$string" '.*\([0-9][.][0-9]\)'
From the info expr
page:
STRING : REGEX'
Perform pattern matching. The arguments are converted to strings and the second is considered to be a (basic, a la GNU `grep') regular expression, with a `^' implicitly prepended. The first argument is then matched against this regular expression. If the match succeeds and REGEX uses `\(' and `\)', the `:' expression returns the part of STRING that matched the subexpression; otherwise, it returns the number of characters matched.
这篇关于Bash脚本正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!