我如何在bash脚本中使用常规的前pressions? [英] How do I use regular expressions in bash scripts?
问题描述
我要检查,如果一个变量的使用常规的前pression有效的年份。读 bash的手册我明白我可以使用操作=〜
看下面的例子,我希望看到不OK但我看到OK。我在做什么错了?
I =测试
如果[$ i =〜200 [78]]
然后
回声OK
其他
回声不OK
科幻
据3.1和3.2之间变化:
这是新功能的简短说明添加到来砸-3.2的bash以来-3.1的发布。
引用的字符串参数的[[命令的=〜运营商现在强制字符串匹配,与其他模式匹配的运营商。
块引用>所以使用它没有这样的行情:
I =测试
如果[$ I =〜200 [78]]];然后
回声OK
其他
回声不OK
科幻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
解决方案It was changed between 3.1 and 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脚本中使用常规的前pressions?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!