string 如何在bash中测试变量是否以字符串开头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4132510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to test that a variable starts with a string in bash?
提问by thomas
For a fixed prefix length I can do it like so:
对于固定前缀长度,我可以这样做:
[ a${filename:0:2} = a.# ] && echo temporary emacs file
How to do it for an arbitrary prefix?
如何为任意前缀做到这一点?
Is there a cleaner way?
有更干净的方法吗?
回答by Ignacio Vazquez-Abrams
[[
's =
operator takes a pattern in the right operand.
[[
的=
运算符在右操作数中采用模式。
var=123
[[ 1234 = $var* ]] && ...
回答by t0r0X
Here the 'regex' version (2015, bash 3.x and newer) of Ignacio's answer, using operator =~
:
这里是 Ignacio 答案的“正则表达式”版本(2015,bash 3.x 和更新版本),使用运算符=~
:
[[ "1234" =~ ^12 ]] && echo y
If you need a dynamic prefix from a variable:
如果您需要来自变量的动态前缀:
var=12
[[ "1234" =~ ^$var ]] && echo y
When using complex regular expressions you can place them in a own variable:
使用复杂的正则表达式时,您可以将它们放在自己的变量中:
var=12
var2=a
regex="^${var}.+${var2}.+$"
[[ "1234a567" =~ $regex ]] && echo y
See also the 'Conditional Constructs' section of the Bash man pageon command [[
:
另请参阅有关命令的 Bash 手册页的“条件构造”部分[[
:
An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's return value is 2. If the shell option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters. Substrings matched by parenthesized subexpressions within the regular expression are saved in the array variable BASH_REMATCH. The element of BASH_REMATCH with index 0 is the portion of the string matching the entire regular expression. The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression.
可以使用额外的二元运算符 =~,其优先级与 == 和 != 相同。使用时,运算符右侧的字符串被视为扩展正则表达式并进行相应匹配(如 regex(3) 中所示)。如果字符串与模式匹配,则返回值为 0,否则为 1。如果正则表达式在语法上不正确,则条件表达式的返回值为 2。如果启用了 shell 选项 nocasematch,则执行匹配时不考虑字母字符的大小写。正则表达式中括号内子表达式匹配的子字符串保存在数组变量 BASH_REMATCH 中。索引为 0 的 BASH_REMATCH 元素是与整个正则表达式匹配的字符串部分。