在shell脚本变量中查找子字符串

时间:2021-01-24 23:48:44

I have a string

我有一个字符串

$VAR="I-UAT"; 

in my shell script code. I need a conditional statement to check if "UAT" is present in that string.

在我的shell脚本代码中。我需要一个条件语句来检查该字符串中是否存在“UAT”。

What command should I use to get either true or false boolean as output? Or is there any other way of checking it?

我应该使用什么命令来获得true或false boolean作为输出?或者还有其他检查方法吗?

6 个解决方案

#1


17  

What shell? Using bash:

什么壳?使用bash:

if [[ "$VAR" =~ "UAT" ]]; then
    echo "matched"
else
    echo "didn't match"
fi

#2


8  

You can do it this way:

你可以这样做:

case "$VAR" in
  *UAT*)
   # code when var has UAT
  ;;
esac

#3


5  

The classic way, if you know ahead of time what string you're looking for, is a case statement:

经典的方法,如果你提前知道你正在寻找什么字符串,是一个案例陈述:

case "$VAR" in
*UAT*) : OK;;
*)     : Oops;;
esac

You can use an appropriate command in place of the : command. This will work with Bourne and Korn shells too, not just with Bash.

您可以使用适当的命令代替:command。这也适用于Bourne和Korn shell,而不仅仅是Bash。

#4


1  

In bash script you could use

在bash脚本中你可以使用

if [ "$VAR" != "${VAR/UAT/}" ]; then
  # UAT present in $VAR
fi

#5


1  

found=`echo $VAR | grep -c UAT`

Then test for $found non-zero.

然后测试$ found非零。

#6


0  

try with grep:

尝试用grep:

$ echo I\-UAT | grep UAT
$ echo $?
0
$ echo I\-UAT | grep UAX
$ echo $?
1

so testing

所以测试

if [ $? -ne 0 ]; then
  # not found
else
  # found
fi

#1


17  

What shell? Using bash:

什么壳?使用bash:

if [[ "$VAR" =~ "UAT" ]]; then
    echo "matched"
else
    echo "didn't match"
fi

#2


8  

You can do it this way:

你可以这样做:

case "$VAR" in
  *UAT*)
   # code when var has UAT
  ;;
esac

#3


5  

The classic way, if you know ahead of time what string you're looking for, is a case statement:

经典的方法,如果你提前知道你正在寻找什么字符串,是一个案例陈述:

case "$VAR" in
*UAT*) : OK;;
*)     : Oops;;
esac

You can use an appropriate command in place of the : command. This will work with Bourne and Korn shells too, not just with Bash.

您可以使用适当的命令代替:command。这也适用于Bourne和Korn shell,而不仅仅是Bash。

#4


1  

In bash script you could use

在bash脚本中你可以使用

if [ "$VAR" != "${VAR/UAT/}" ]; then
  # UAT present in $VAR
fi

#5


1  

found=`echo $VAR | grep -c UAT`

Then test for $found non-zero.

然后测试$ found非零。

#6


0  

try with grep:

尝试用grep:

$ echo I\-UAT | grep UAT
$ echo $?
0
$ echo I\-UAT | grep UAX
$ echo $?
1

so testing

所以测试

if [ $? -ne 0 ]; then
  # not found
else
  # found
fi