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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6823484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:47:44  来源:igfitidea点击:

Find substring in shell script variable

bashshellscriptingsubstring

提问by batty

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 布尔值作为输出?或者有没有其他的检查方法?

采纳答案by Andrew Clark

What shell? Using bash:

什么壳?使用 bash:

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

回答by Diego Sevilla

You can do it this way:

你可以这样做:

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

回答by Jonathan Leffler

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

如果您提前知道要查找的字符串,那么经典的方法是case声明:

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.

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

回答by jman

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

Then test for $found non-zero.

然后测试 $found 非零。

回答by Neil

In bashscript you could use

bash脚本中你可以使用

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

回答by marcelog

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