如何在 bash shell 脚本变量中查找子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15118934/
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
how to Find a substring in a bash shell script variable
提问by Boby
I have a variable like below.
我有一个像下面这样的变量。
variable = This script is not found
if [[ "$variable" = ~ "not found" ]];
then
echo "Not Found"
else
echo "Its there"
if
while executing im getting below err,
在执行时我低于错误,
line 4: syntax error in conditional expression
./test.sh: line 4: syntax error near `found"'
./test.sh: line 4: `if [[ "$variable" = ~ "not found" ]]; '
could anyone point me, What im missing here?
谁能指出我,我在这里缺少什么?
回答by Quentin Perez
LIST="some string with a substring you want to match"
SOURCE="substring"
if echo "$LIST" | grep -q "$SOURCE"; then
echo "matched";
else
echo "no match";
fi
Good Luck ;)
祝你好运 ;)
回答by William
Compare this with your version at the indicated points:
将此与您在指定点的版本进行比较:
variable="This script is not found" # <--
if [[ "$variable" =~ "not found" ]] # <--
then
echo "Not Found"
else
echo "Its there"
fi # <--
You can't put spaces around = in an assignment, and you need to quote a string literal that has spaces. You don't need a trailing ; if you're going to put then on its own line. And an if-then ends with "fi" not "if".
您不能在赋值中在 = 周围放置空格,并且您需要引用包含空格的字符串文字。你不需要尾随;如果你打算把那么放在它自己的行上。if-then 以“fi”而不是“if”结尾。
回答by jfelipesp
here is a correct construction of your if statement
这是您的 if 语句的正确构造
if [[ "$variable" =~ "not found" ]]; then
echo "Not Found";
else
echo "Its there";
fi
回答by Aryan
I have tried below codes which always return same result either in true or false
我试过下面的代码,它们总是以真或假返回相同的结果
if [[ "$variable" =~ "not found" ]]; then
echo "Not Found";
else
echo "Its there";
fi