如何在 bash 脚本中使用正则表达式? [英] How do I use regular expressions in bash scripts?
问题描述
我想使用正则表达式检查变量是否具有有效年份.阅读 bash 手册 我知道我可以使用运算符=~
I want to check if a variable has a valid year using a regular expression. Reading the bash manual I understand I could use the operator =~
查看下面的示例,我希望看到不正常",但我看到的是正常".我做错了什么?
Looking at the example below, I would expect to see "not OK" but I see "OK". What am I doing wrong?
i="test"
if [ $i=~"200[78]" ]
then
echo "OK"
else
echo "not OK"
fi
推荐答案
在 3.1 和 3.2 之间发生了变化:
It was changed between 3.1 and 3.2:
这是对自 bash-3.1 发布以来添加到 bash-3.2 的新特性的简要描述.
This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.
引用 [[ 命令的 =~ 运算符的字符串参数现在会强制字符串匹配,就像其他模式匹配运算符一样.
Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.
所以使用它而不使用引号:
So use it without the quotes thus:
i="test"
if [[ $i =~ 200[78] ]] ; then
echo "OK"
else
echo "not OK"
fi
这篇关于如何在 bash 脚本中使用正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!