2013-09-10 36 views
0

我在做bash,我試着測試給定變量x中的子字符串「world」。我有一部分代碼工作。但另一個不工作。我想弄清楚爲什麼bash substring正則表達式匹配通配符

第一個是工作

x=helloworldfirsttime 
world=world 
if [[ "$x" == *$world* ]];then 
    echo matching helloworld 

第二個是不工作

x=helloworldfirsttime 
if [[ "$x" == "*world*" ]];then 
    echo matching helloworld 

如何讓第二個工作,而無需使用變量,如第1種方法

有人可以爲我解決第二個問題..謝謝

回答

2
x=helloworldfirsttime 
$ if [[ "$x" == *world* ]]; then echo MATCHING; fi 
MATCHING 

這工作,因爲bash的內置[[運營商把一個==測試作爲圖案的右手邊:

==並使用!=運算符時,將運算符右側的字符串用作模式並執行模式匹配。

0

下一次,如果你想提供patters用空格,你可以只引用它周圍""'',只是你必須把外面的模式字符:

[[ "$x" == *"hello world"* ]] 

[[ "$x" == *'hello world'* ]] 

[[ "$x" == *"$var_value_has_spaces"* ]]