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

时间:2021-01-09 20:45:19

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 =~

我想使用正则表达式检查一个变量是否有一个有效的年份。阅读bash手册,我知道我可以使用操作=~

Looking at the example below, I would expect to see "not OK" but I see "OK". What am I doing wrong?

看看下面的例子,我希望看到“不OK”,但是我看到了“OK”。我做错了什么?

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

2 个解决方案

#1


111  

It was changed between 3.1 and 3.2:

在3.1和3.2之间发生了变化:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

这是对自bash-3.1发布以来添加到bash-3.2中的新特性的简要描述。

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

#2


8  

You need spaces around the operator =~

你需要在操作符附近留有空格=~

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

#1


111  

It was changed between 3.1 and 3.2:

在3.1和3.2之间发生了变化:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

这是对自bash-3.1发布以来添加到bash-3.2中的新特性的简要描述。

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

#2


8  

You need spaces around the operator =~

你需要在操作符附近留有空格=~

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