如何在bash脚本中使用正则表达式?

idr*_*sid 83 regex bash conditional

我想使用正则表达式检查变量是否具有有效年份.阅读bash手册我明白我可以使用operator =〜

看下面的例子,我希望看到"不行",但我看到"OK".我究竟做错了什么?

i="test"
if [ $i=~"200[78]" ]
then
  echo "OK"
else
  echo "not OK"
fi
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 116

它在3.1和3.2之间变化:

这是自bash-3.1发布以来添加到bash-3.2的新功能的简洁描述.

引用[[command's =〜运算符]的字符串参数现在强制字符串匹配,就像其他模式匹配运算符一样.

因此,在没有引号的情况下使用它:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi
Run Code Online (Sandbox Code Playgroud)

  • @Alderath:使用`a\\ + b`来逃避空格和加号. (5认同)

小智 8

你需要在运算符周围的空格=〜

i="test"
if [[ $i =~ "200[78]" ]];
then
  echo "OK"
else
  echo "not OK"
fi

  • paxdiablo的回答是正确的,在这里添加空格并没有帮助(你现在也得到2008年的"不行",唯一匹配的字符串字面意思是"200 [78]"). (3认同)