检查字符串是否以某个字符串开头并以数字结尾 - sh 脚本

check if string start with some string and ending in a digit - sh script

我想检查 shell 脚本中某个变量是否以某个字符串 (A-) 开头并以数字结尾。

我的脚本(test.sh):

#!/bin/bash

VAR=A-1

if [[ $VAR =~ A-*[0-9 ] ]]; then
        echo "yes"
else
        echo "no"
fi

我在 运行 sh test.sh:

之后得到的错误

test.sh: 5: test.sh: [[: not found

我试图将让步更改为: if [ $VAR =~ A-*[0-9 ] ]; then 并收到此错误:test.sh: 5: [: A-1: unexpected operator

sh test.sh 不使用 bash 到 运行 脚本,它使用 sh,这取决于系统,可能不具有与 bash.

您可以使用:

bash test.sh

或者:

chmod a+rx test.sh # one time only
./test.sh          # your script is set to use /bin/bash in the #! line.

试试这样的:${VAR:${#VAR}-1:1}

比照。 https://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html

[[ "${VAR:${#VAR}-1:1}" =~ [0-9] ]] && echo yes

应始终引用变量: VAR="A-1"

您的代码中的问题与您在正则表达式中定义的 space in the square brackets: [...] 有关:[0-9 ]。 里面不应该有任何space。

检查某个变量是否以 A- 开头并以 digit 结尾的正确代码应该是:

#!/bin/bash

VAR="A-1"

if [[ "$VAR" =~ ^A-.*[0-9]$ ]]; then
        echo "yes"
else
        echo "no"
fi

请注意变量 VAR 周围的 double quotes

根据 OP 的评论,似乎正在使用 sh 而不是 bash ,因为正则表达式匹配运算符: =~sh 中不起作用并且 bash 具体。

使用 sh 更新代码:

#!/bin/sh

VAR="A-1"

if echo "$VAR"| grep -Eq "^A-.*[0-9]$"
  then
    echo "Yes"
else
    echo "no"
fi

用于匹配 starts with A- and ends with a digit 字符串的正则表达式 应该是:^A-.*[0-9]$ 或更严格地说 ^A-.*[[:digit:]]$。 那么请将您的 scpipt 修改为:

#!/bin/bash

VAR="A-1"

if [[ $VAR =~ ^A-.*[0-9]$ ]]; then
    echo "yes"
else
    echo "no"
fi

然后用 bash test.sh 调用它,而不是 sh test.sh