2017-04-27 29 views
0

我想寫一個bash腳本,它會告訴兩個字符串是否具有相似的值。我公司生產的此bash腳本:Ubuntu的bash腳本字符串包含類似的詞

#!/bin/bash 
value="java.lang.NullPointerException" 
if [[ "java.lang.NullPointerException" = "$value" || "java.lang.NullPointerException" == "$value"* ]]; then 
    echo "Match" 
fi 

基本上我想才達到的東西,就是如果兩個字符串的值相等或非常相似的兩側,但在中間匹配的文本,然後回聲「匹配」。

我已經嘗試了一些資源,但無法讓這個例子工作。我已經採取一看:

  1. In bash, how can I check if a string begins with some value?
  2. How to test that a variable starts with a string in bash?
  3. https://ubuntuforums.org/showthread.php?t=1118003

請注意,這些值最終會從一個文本文件,因此它們的值將是變量的形式。我嘗試過不同的方法,但似乎沒有得到它的工作。我只是想得到這個如果陳述工作。它適用於匹配文本,但不適用於任何一方的值。值可能是「java.lang.NullPointerException:Unexpected」或「Unexpected java.lang.NullPointerException」。

+0

你有你的操作數命令錯誤:'in =「test this」; [[「$ in」=「test」*]] && echo ok'正常工作(並且不需要額外的'='測試);這是最短的值,必須用作帶'*'的模式 – Aaron

+0

謝謝。這工作。 –

+0

不客氣!我建議你刪除你的問題,因爲它現在已經解決了,只是關於你所鏈接問題的答案的錯誤實現。 – Aaron

回答

0
#!/bin/bash 
value="java.lang.NullPointerException" #or java.lang.NullPointerException: Unexpected 
if [[ $value == *"java.lang.NullPointerException"* ]]; 
then 
    echo "Match" 
fi 
+0

雖然這可能是對這個問題的回答,並且被問到的人可能會鄙視它,但是如果你可以在你做的事情上添加一些解釋,這將是很好的,所以它也可以幫助更多的讀者,這可能會偶然遇到這個問題。 – derM

+0

@derM這是一個單行!應該很容易在[Bash手冊](http://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html#index-_005b_005b)上找到[Stackexchange](http ://stackoverflow.com/questions/669452/is-preferable-over-in-bash-scripts)或[Bash常見問題](http://mywiki.wooledge.org/BashFAQ/031)。 – ceving

+1

@der:'s/contempt/content /'! –

0

一個簡單的和便攜式(POSIX兼容)通配符匹配技術是使用case語句,而不是if。對於你的例子,這看起來像

#!/bin/sh 
value="java.lang.NullPointerException" 
case "$value" in 
*java.lang.NullPointerException*) echo Match;; 
esac