bash 子串正则表达式匹配通配符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18730509/
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
bash substring regex matching wildcard
提问by runcode
I am doing bash , i try to test if the substring "world" in the given variable x. I have part of code working. But the other one not working. I want to figure out why
我正在做 bash ,我尝试测试给定变量 x 中的子字符串“world”。我有一部分代码在工作。但另一个不起作用。我想弄清楚为什么
First one is working
第一个正在工作
x=helloworldfirsttime
world=world
if [[ "$x" == *$world* ]];then
echo matching helloworld
Second one is not working
第二个不工作
x=helloworldfirsttime
if [[ "$x" == "*world*" ]];then
echo matching helloworld
How to make second one work without using variable like the 1st method
如何在不使用第一种方法的变量的情况下使第二个工作
Can someone fix the second one for me.. thanks
谁能帮我修第二个..谢谢
回答by Andrew Clark
Just remove the quotes:
只需删除引号:
x=helloworldfirsttime
if [[ "$x" == *world* ]]; then
echo matching helloworld
fi
Note that this isn't regex (a regex for this would look something like .*world.*
). The pattern matching in bash is described here:
http://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html
请注意,这不是正则表达式(用于此的正则表达式类似于.*world.*
)。这里描述了 bash 中的模式匹配:http:
//www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html
回答by Phil
x=helloworldfirsttime
$ if [[ "$x" == *world* ]]; then echo MATCHING; fi
MATCHING
This works because bash's builtin [[
operator treats the right-hand-side of an ==
test as a pattern:
这是有效的,因为 bash 的内置[[
运算符将测试的右侧==
视为一种模式:
When the
==
and!=
operators are used, the string to the right of the operator is used as a pattern and pattern matching is performed.
使用
==
and!=
运算符时,运算符右侧的字符串用作模式并执行模式匹配。
回答by konsolebox
Next time if you want to provide patters with spaces you could just quote it around ""
or ''
, only that you have to place the pattern characters outside:
下次如果你想为模式提供空格,你可以在""
或周围引用它''
,只是你必须将模式字符放在外面:
[[ "$x" == *"hello world"* ]]
[[ "$x" == *'hello world'* ]]
[[ "$x" == *"$var_value_has_spaces"* ]]
回答by Alessandro Gastaldi
You shold use without quotes and the =~
operator.
你不使用引号和=~
运算符。
TEXT=helloworldfirsttime
SEARCH=world
if [[ "$TEXT" =~ .*${SEARCH}.* ]]; then echo MATCHING; else echo NOT MATCHING; fi
TEXT=hellowor_ldfirsttime
if [[ "$TEXT" =~ .*${SEARCH}.* ]]; then echo MATCHING; else echo NOT MATCHING; fi